Apache组织开发了一套用于操作JavaBean的API,这套API考虑到了很多实际开发中的应用场景,因此在实际开发中很多程序员使用这套API操作JavaBean,以简化程序代码的编写。
Beanutils工具包的常用类:
•BeanUtils
•PropertyUtils
•ConvertUtils.regsiter(Converter convert, Class clazz)
•自定义转换器
package com.kevin; import static org.junit.Assert.*; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.Converter; import org.apache.commons.beanutils.locale.converters.DateLocaleConverter; import org.junit.Test; public class BeanDemo1 { @Test public void test1() throws IllegalAccessException, InvocationTargetException { Person p1 = new Person("kevin"); System.out.println(p1.getName()); BeanUtils.setProperty(p1, "name", "xiang"); System.out.println(p1.getName()); } @Test public void test2() throws IllegalAccessException, InvocationTargetException { String name = "xiangjie"; String age = "23"; String birthday = "1980-09-09"; //自己注册日期转换器:String---> Date,实际开发可以用包里实现好的。 ConvertUtils.register(new Converter() { @Override public Object convert(Class type, Object value) { if(value == null) { return null; } if( !(value instanceof String) ) { throw new ConversionException("只支持String类型的转换"); } String str = (String) value; if( str.trim().equals("") ) { return null; } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { return df.parse(str); } catch (ParseException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } } }, Date.class); Person p2 = new Person(); BeanUtils.setProperty(p2, "name", name); BeanUtils.setProperty(p2, "age", age); BeanUtils.setProperty(p2, "birthday", birthday); System.out.println(p2.getName()); System.out.println(p2.getAge()); System.out.println(p2.getBirthday()); } @Test public void test3() throws IllegalAccessException, InvocationTargetException { String name = "xiangjie"; String age = "23"; String birthday = "1980-09-09"; //用官方实现的包, 但是有问题 ConvertUtils.register(new DateLocaleConverter(), Date.class); Person p2 = new Person(); BeanUtils.setProperty(p2, "name", name); BeanUtils.setProperty(p2, "age", age); BeanUtils.setProperty(p2, "birthday", birthday); System.out.println(p2.getName()); System.out.println(p2.getAge()); System.out.println(p2.getBirthday().toString()); } @Test public void test4() throws IllegalAccessException, InvocationTargetException { Map map = new HashMap(); map.put("name", "aaa"); map.put("age", "12"); //填充,如果包含有Date这种类型的数据,一样要注册转换器 Person bean = new Person(); BeanUtils.populate(bean, map); System.out.println(bean.getName()); System.out.println(bean.getAge()); } }