码迷,mamicode.com
首页 > 编程语言 > 详细

javaweb 学习:BeanUtils框架/工具

时间:2018-04-16 11:06:36      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:javaweb 学习:BeanUtils

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

javaweb 学习:BeanUtils框架/工具

标签:javaweb 学习:BeanUtils

原文地址:http://blog.51cto.com/357712148/2103793

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!