Sun公司的內省API過於繁瑣,因此Apache組織結合不少實際開發中的應用場景開發了一套簡單、易用的API操做Bean的屬性——BeanUtils,在Beanutil中能夠直接進行類型的自動轉換。apache
BeanUtil工具包下載:ide
1,登陸http://commons.apache.org/beanutils/工具
2, 點擊Downloadspa
3, 點擊Commons BeanUtils 1.8.3-bin.tar.gz進行下載就OK了orm
使用BeanUtil對象
在項目中導入commons-beanutils-1.8.3.jar包便可開發
BeanUtil的應用get
Beanutils工具包的經常使用類:string
1,BeanUtilsit
2,PropertyUtils
3,ConvertUtils.regsiter(Converter convert, Class clazz)
4,自定義轉換器
在這裏我舉了幾個不一樣的實例:
實例1代碼:
publicvoid test1() throws Exception {
// 加載類
Class cls = Class.forName("cn.csdn.beanutil.Student");
// 建立對象
Student bean = (Student) cls.newInstance();
// 經過beanutil給name屬性賦值
BeanUtils.setProperty(bean, "name", "wangli");
Object obj = BeanUtils.getProperty(bean, "name");
System.out.println(obj);
}
實例2代碼:
publicvoid test2() throws Exception {
Date da = new Date();
// 加載類
Class cls = Class.forName("cn.csdn.beanutil.Student");
// 建立對象
Student bean = (Student) cls.newInstance();
// 經過Beanutil給屬性賦值
BeanUtils.setProperty(bean, "birthday", da);
System.out.println(bean.getBirthday());
}
實例3代碼:
publicvoid test4() throws Exception {
//建立對象
Student bean = new Student();
//經過ConvertUtils自動轉換日期類型
ConvertUtils.register(new DateLocaleConverter(), Date.class);
//經過BeanUtils給屬性賦值
BeanUtils.setProperty(bean, "birthday", "2003-10-30");
//執行
System.out.println(bean.getBirthday());
}
實例4代碼:
//自定義轉換器
publicvoid test5() throws Exception{
//建立對象
Student bean = new Student();
//經過ConvertUtils自定義轉換日期類型
ConvertUtils.register(new Converter() {
public Object convert(Class type, Object value) {
if (value == null) {
returnnull;
} else {
//定義日期格式
SimpleDateFormat sdi = new SimpleDateFormat("yyyy-MM-dd");
Date dt = null;
try {
dt = sdi.parse((String) value);
} catch (ParseException e) {
//拋出異常
thrownew ConversionException("日期格式轉化不對.....");
}
return dt;
}
}
}, Date.class);
//經過BeanUtils給屬性賦值
BeanUtils.setProperty(bean, "birthday", "1990-13-33");
//執行
System.out.println(bean.getBirthday());
}