BeanUtils使用

【一】日期类型

1.public class Student {
    private String name;
    private int age;
    private Date birth;

   public String getName() {
        return name;
    }

....

}

2.测试

public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        // TODO Auto-generated method stub
       Class studentClass=Class.forName("com.beanutil.Student");
       Student st=(Student)studentClass.newInstance();
       BeanUtils.setProperty(st, "name", "my name is ");
       String strName=BeanUtils.getProperty(st, "name");
       System.out.println("strName:"+strName);
       
       Student student=new Student();
       ConvertUtils.register(new Converter(){

        @Override
        public Object convert(Class type, Object value) {
            if(value==null){
                return null;
            }
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd");
            Date dt=null;
            try {
                dt=sdf.parse((String)value);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return dt;
        }
           
       }, Date.class);
       BeanUtils.setProperty(student, "birth", "1985-04-28");
       System.out.println("birth:"+student.getBirth());
    }

 

3.Map类型

public class BeanTestEntity {
    private String name;
    private HashMap address = new HashMap();
    private String[] otherInfo;
    private ArrayList product;
    private ArrayList employee;
    private HashMap telephone;

    public String getName() {
        return name;
.... 

 }

4.测试

public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
      BeanTestEntity test=new BeanTestEntity();
      test.setName("hahha");
      System.out.println("name:"+BeanUtils.getProperty(test, "name"));
      HashMap map=new HashMap();
      map.put("1", "13453978888");
      map.put("2", "15960668888");
      BeanUtils.setProperty(test, "telephone", map);
      System.out.println(BeanUtils.getProperty(test,"telephone(1)"));
      BeanTestEntity test2=new BeanTestEntity();
      BeanUtils.copyProperties(test2, test);
      System.out.println("test2 name:"+BeanUtils.getProperty(test2, "name"));
  }

 

posted @ 2016-04-15 11:02  IT一族  阅读(127)  评论(0编辑  收藏  举报