一、BeanUtils介紹
BeanUtils是apache的開發庫;
為了使用BeanUtils,需要匯入
(1)common-logging-1.1.1.jar
(2)common-beanutils.jar
二、BeanUtils開發(1)設定屬性;(2)註冊轉換器;(3)自訂轉換器;(4)大量設定屬性;
注意:JavaBean必須是public的,不然BeanUtils會拋異常;
package org.xiazdong.beanutils;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;import org.xiazdong.Person;public class Demo01 {// 設定屬性@Testpublic void test1() throws Exception {Person p = new Person();BeanUtils.setProperty(p, "name", "xiazdong");BeanUtils.setProperty(p, "age", 20);System.out.println(p.getName());System.out.println(p.getAge());}// 自訂轉換器@Testpublic void test2() throws Exception {Person p = new Person();ConvertUtils.register(new Converter() {@Overridepublic 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());}// 使用內建的轉換器@Testpublic 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());}// 使用內建的轉換器@Testpublic void test4() throws Exception {Map map = new HashMap();map.put("name", "xiazdong");map.put("age", "20");map.put("birth", "2010-10-10");ConvertUtils.register(new DateLocaleConverter(), Date.class);Person p = new Person();BeanUtils.populate(p, map);System.out.println(p.getAge());System.out.println(p.getBirth());}}