04-体验一下apache组织封装的BeanUtil工具包
apache 自己为程序员们封装了一个专门用于处理的工具类,其功能有(数据类型会自动转成与JavaBean相关的)
map转javabean
javabean转map
javabean对象复制
获取javabean对象属性值
设置javabean对象属性值…………
两个相关jar包文件 Build Path到项目当中去
commons-beanutils-1.9.2.jar
commons-logging-1.2.jar

1.将Map转换成JavaBean对象
/** * 刘诗华 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Map<String, Object> m=new HashMap<String, Object>(); m.put("id", "28"); m.put("userName", "刘诗华"); m.put("password", "123456"); User user=new User(); //BeanUtils.copyProperties(dest, orig); dest:目标 orig:源 BeanUtils.copyProperties(user,m); System.out.println(user); //结果:User(id=28, userName=刘诗华, password=123456) Integer id = user.getId(); //我们设置给Map集合的时候,给的是一个字符串,BeanUtils工具自动帮我们转换成包装类Integer类型 System.out.println(id); }
2.JavaBean对象复制数据
/** * 刘诗华 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { User orig=new User(28,"罗小胖","456456"); //源对象 User dest=new User(); //目标对象 空对象 BeanUtils.copyProperties(dest,orig); //JavaBean对象复制数据 System.out.println(dest); //User(id=28, userName=罗小胖, password=456456) }
3.设置Date时间格式转换
/** * 申请注册时间格式 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //源数据 Map<String, Object> m=new HashMap<String, Object>(); m.put("id", ""); m.put("userName", "刘诗华"); m.put("password", "123456"); m.put("hireDate", "2018/11/19"); //目标数据 User user=new User(); //时间数据格式对象 DateConverter converter=new DateConverter(); //converter.setPattern("yyyy-MM-dd HH:mm:ss"); //单个数据格式 //一组时间格式 String[] pattern=new String[3]; pattern[0]="yyyy-MM-dd HH:mm:ss"; pattern[1]="yyyy-MM-dd"; pattern[2]="yyyy/MM/dd"; converter.setPatterns(pattern); //如果Id上面没有数据,则设置为null IntegerConverter integerConverter=new IntegerConverter(null); ConvertUtils.register(integerConverter, Integer.class); //注册Date时间对象格式 ConvertUtils.register(converter, Date.class); //开始复制数据信息 BeanUtils.copyProperties(user, m); System.out.println(user); //User(id=null, userName=刘诗华, password=123456, hireDate=Mon Nov 19 00:00:00 CST 2018) }

浙公网安备 33010602011771号