天天看點

BeanUtils 的使用 | 學習筆記

開發者學堂課程【JSP 快速入門: BeanUtils 的使用】學習筆記,與課程緊密聯系,讓使用者快速學習知識。

課程位址:

https://developer.aliyun.com/learning/course/33/detail/725

BeanUtils 的使用

JavaBean 的規範

1.必須要有一個預設構造器

2. 提供 get/set 方法,如果隻有 get 方法,那麼這個屬性是隻讀屬性

3. 屬性:有 get/set 方法的成員,述可以沒有成員,隻有 get/set 方法,屬性名稱由get/set 方法來決定!而不是成員名稱!

4.方法名稱滿足一定的規範,那麼他就是是屬性! boolean 類型的屬性, 它的讀方法可以是 is 開頭,也可以是 get 開頭!

例如:

public class Person {

private String username;

private int age;

private String gender;

private boolean bool ;

public boolean isBool() {

return bool;

}

public void setBool (boolean bool) {

this.bool = bool;

}

public string getId() {

retarn "fdsafdafdas";

}

public  String  getName(){

内省就是通過反射來操作 javabean ,但他比使用反射要友善些!

我們需要提供 javaBean 類!

内省:

内省類--> Bean 資訊-->屬性描述符--> 屬性的 get/set 對應的 Method ! --- >可以反射了!

commons-beanutils , 它是依賴内省完成!

導包:

conmons -be anucils . jar

conmong- logging. jar

public class Demo1 l

@Test

public void fun1() throws Exception (

String className . "cn. itcast. domain. Person";

class clazz = class. forName (className) ;

object bean = clazz. newInstance() ;

BeanUtils. setProperty(bean, "name", "張三");

BeanUtils. setProperty(bean, "age", "23");

BeanUtilg. setProperty(bean,"gender",男");

BeanUtils. setProperty(bean, "xxx", "XXX");

BeanUcils. getProperty(bean, "age");

System. out. println (age);

System. out. println (bean);

把 map 中的屬性直接封裝到一個 bean 中

Map: ("username" :"zhangSan", "password", "123")

GTest

public void fun2 () {

Map map . new HashMap();

map.put ("username", " zhangSan") ;

map.put ("password", "123");

User user=new User() ;

BeanUtils.populate(user, map);

這就是資料的轉換。