BeanUtils使用
JAVA在Web开发项目中,经常会接收各种参数,并将这些参数保存到对象里面去,比如,http://127.0.0.1/Servlet/?username=liqiu&password=123456&age=29。需要将这些内容保存在User对象里面去,User.java代码如下:
public class User { private String username; private String password; private int age; public String getUsername() { return username; } ............................. }
那么,如果不使用BeanUtils,需要一个参数一个参数的判断,转换和赋值,反之:
Map map = request.getParameterMap(); User user = new User(); try { BeanUtils.populate(user, map); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); }
当然也有略复杂的情况,比如传输时间类型的数据
package com.taobao.beanutils; .............................................public class Demo01 { // 自定义转换器 @Test public void test2() throws Exception { Person p = new Person(); ConvertUtils.register(new Converter() { @Override public Object convert(Class type, Object value) { if (value == null) { return null; } if (!(value instanceof String)) { throw new ConversionException("conversion error"); } String str = (String) value; if (str.trim().equals("")) { return null; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { return sdf.parse(str); } catch (ParseException e) { throw new RuntimeException(e); } } }, Date.class); BeanUtils.setProperty(p, "birth", "2011-10-10"); System.out.println(p.getBirth().toLocaleString()); } // 使用内置的转换器 @Test public void test3() throws Exception { Person p = new Person(); ConvertUtils.register(new DateLocaleConverter(), Date.class); BeanUtils.setProperty(p, "birth", "2011-10-10"); System.out.println(p.getBirth().toLocaleString()); } }