1.注意需要两个jar包: commons-beanutils-1.8.3.jar 和 commons-logging-1.1.3.jar
public class Admin {//省略getset等通用方法 private int id; private String username; private String pwd; private Date date; } public class APP { @Test public void testBeanUtils() throws Exception, InvocationTargetException{ Admin admin = new Admin(); //方式1 admin.setUsername("妹子"); admin.setPwd("123"); System.out.println(admin); //方式2 BeanUtils.copyProperty(admin, "username", "zhangsan"); BeanUtils.setProperty(admin, "pwd", "5555"); System.out.println(admin.getUsername()); System.out.println(admin.getPwd()); //方式3 Map<String,Object> map = new HashMap<>(); map.put("username", "zhangsan"); map.put("pwd", "586665"); BeanUtils.populate(admin, map); System.out.println(admin); //方式4 Date 转化 ,需要注册一个转化器 ConvertUtils.register(new DateConvert_MY(), Date.class); Map<String,Object> map2= new HashMap<>(); map2.put("username", "zhangsan"); map2.put("pwd", "586665"); map2.put("date", "2016-09-24"); BeanUtils.populate(admin, map2); System.out.println(admin); } } class DateConvert_MY implements Converter{ @Override public Object convert(Class type, Object value) { if(Date.class != type) return null; if(null == value || "".equals(value.toString().trim())) return null; try { return new SimpleDateFormat("yyyy-MM-dd").parse(value.toString()); } catch (ParseException e) { throw new RuntimeException(e); } } }