3 BeanUtils框架/工具(APACHE开源组织开发)
1)BeanUtils框架能够完成内省的一切功能,而且优化
2)BeanUtils框架能够对String<->基本类型自动转化
3)BeanUtils框架自定义转换器:
ConvertUtils.register( 转换规则 ,目标对象的Class)
4)向BeanUtils框架注册自定义转换器必须放在bu.setProperty()代码之前
5)使用BeanUtils内置String->Date的转换器:
ConvertUtils.register(new DateLocaleConverter(),java.util.Date.class);
``
`
public class Student {
private String name;
private int age;
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}`
@Test
public void test1() throws Exception
{
Student s = new Student();
BeanUtils bu = new BeanUtils();
ConvertUtils.register(new DateLocaleConverter(), java.util.Date.class);
bu.setProperty(s, "name", "李玟");
bu.setProperty(s, "age", "123213");
bu.setProperty(s,"birthday","2011-10-09");
String name = bu.getProperty(s, "name");
String age = bu.getProperty(s, "age");
String birthday = bu.getProperty(s,"birthday");
System.out.println("name = "+name);
System.out.println("age = "+age);
System.out.println("birthday="+new Date(birthday).toLocaleString());
}
自定义
//向BeanUtils框架注册自定义的转换器(String->java.util.Date)
ConvertUtils.register(new Converter(){
public Object convert(Class clazz, Object type) {
//参数一:java.util.Date.class(目标类型)
//参数二:是传入的参数类型,即java.lang.String
String strBirthday = (String) type;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(strBirthday);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
},java.util.Date.class);
原文地址:http://blog.51cto.com/357712148/2103793
时间: 2024-10-04 17:05:20