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);

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐