引入jar包(需要引入依赖的日志jar包)
Person p = new Person();
p.setName("Daisy");
p.setAge(12);
//对象的copy
Person newP = new Person();
BeanUtils.copyProperties(newP,p);
//对象属性的拷贝
BeanUtils.copyProperty(p,"name","juaner");
BeanUtils.setProperty(p,"age",10);//如果属性不存在,不会报错
//map对象拷贝到对象中,servlet中请求数据封装到parameterMap中
// 可以用来初始化bean
Map<String,Object> propMap = new HashMap<String, Object>();
propMap.put("name","tom");
propMap.put("age",25);
propMap.put("email","123@126.com");
BeanUtils.populate(p,propMap);
自定义类型转换器:
//模拟表单提交 String name="jack"; int age = 25; String birth = "1990-10-10"; Person p = new Person(); //注册日期类型转换器,自定义的方式 ConvertUtils.register(new Converter() { @Override public Object convert(Class aClass, Object o) { if(aClass != Date.class) return null; if(o == null||"".equals(o.toString().trim()) ) return null; try { SimpleDateFormat format =
new SimpleDateFormat("yyyy-mm-dd"); return format.parse(o.toString()); }catch (ParseException e){ throw new RuntimeException(e); } } }, Date.class); BeanUtils.setProperty(p,"name",name); BeanUtils.setProperty(p,"age",age); BeanUtils.setProperty(p,"birth",birth);
使用BeanUtils组件提供的转换器:
//模拟表单提交 String name="jack"; int age = 25; String birth = "1990-10-25"; //使用组件提供的转换器工具类,不支持空格 ConvertUtils.register(new DateLocaleConverter(),Date.class); Person p = new Person(); BeanUtils.setProperty(p,"name",name); BeanUtils.setProperty(p,"age",age); BeanUtils.setProperty(p,"birth",birth);