BeanUtils
commons-beanutils 是apache commons子项目中的一个软件包,其主要目的是利用反射机制对 JavaBean 的属性进行处理。
Maven:
commons-beanutils
commons-beanutils
1.9.3
使用BeanUtils工具封装用户提交的数据。
可以省略基本数据类型的转型的问题。进而提高代码的开发效率。
public static void main(String[] args)throws Exception {
String name = "shuxue";
String author = "ly";
String price = "100.00";
String date = "2021-3-3";
Book book = new Book();
// 设置给指定的对象
BeanUtils.setProperty(book, "name", name);
BeanUtils.setProperty(book, "author", author);
BeanUtils.setProperty(book, "price",price );
//测试
System.out.println(book);
}
自定义一个类型转换器类。
public static void main(String[] args)throws Exception {
String name = "shuxue";
String author = "ly";
String price = "100.00";
String date = "2020-3-3";
Book book = new Book();
ConvertUtils.register(
new Converter(){
// 回调方法
@Override
public Object convert(Class type, Object value) {
if(value == null){
return null;
}
// 转换为String
String data = (String)value;
// 将指定格式的字符串转换为Date
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(data);
return date;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
},
Date.class);
// 属性设置给指定的对象
BeanUtils.setProperty(book, "name", name);
BeanUtils.setProperty(book, "author", author);
BeanUtils.setProperty(book, "price",price );
BeanUtils.setProperty(book, "date",date );
// 查看
System.out.println(book);
}
实现封装好的JavaBean对象的属性拷贝。
Book copy = new Book();
System.out.println(copy);
PropertyUtils.copyProperties(copy, book);
System.out.println(copy);
|