程序中对javabean的操作很频繁, 所以apache提供了一套开源的api,方便对javabean的操作!即BeanUtils组件。
BeanUtils组件, 作用是简化javabean的操作!
1、使用BenUtils组件:
- 引入commons-beanutils-1.8.3.jar核心包
- 引入日志支持包: commons-logging-1.1.3.jar
如果缺少日志jar文件,报错:
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.apache.commons.beanutils.ConvertUtilsBean.<init>(ConvertUtilsBean.java:157)
at org.apache.commons.beanutils.BeanUtilsBean.<init>(BeanUtilsBean.java:117)
at org.apache.commons.beanutils.BeanUtilsBean$1.initialValue(BeanUtilsBean.java:68)
at
2、实例, 基本用法
方法1: 对象属性的拷贝
// 两种方法效果一样
BeanUtils.copyProperty(admin, "userName", "jack");
BeanUtils.setProperty(admin, "age", 18);
方法2: 对象的拷贝
BeanUtils.copyProperties(newAdmin, admin);
方法3: map数据拷贝到javabean中
【注意:map中的key要与javabean的属性名称一致】
BeanUtils.populate(adminMap, map);
对日期对象的转换
需要注册日期类型转换器,有两种方法
1、自己写日期类型转换器
@Test
public void test() throws Exception{
int id = 1;
String name = "eric";
int age = 19;
String birth = " ";
Admin admin = new Admin();
// 注册日期转换器:1、自定义类型转换器
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class arg0, Object arg1) {
if(arg0!=Date.class)
return null;
if(arg1==null || "".equals(arg1.toString().trim()))
return null;
try {
// 字符串转换为日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.parse(arg1.toString());
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}, Date.class);
BeanUtils.setProperty(admin, "birth", birth);
BeanUtils.setProperty(admin, "id", id);
BeanUtils.setProperty(admin, "name", name);
BeanUtils.setProperty(admin, "age", age);
System.out.println(admin);
}
2、使用第三方日期类型转换器
// 使用组件提供的类型转换器
@Test
public void test1() throws Exception{
int id = 1;
String name = "eric";
int age = 19;
String birth = "1992-11-20";
Admin admin = new Admin();
// 注册日期转换器:1、自定义类型转换器
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.setProperty(admin, "birth", birth);
BeanUtils.setProperty(admin, "id", id);
BeanUtils.setProperty(admin, "name", name);
BeanUtils.setProperty(admin, "age", age);
System.out.println(admin);
}