BeanUtils學習總結
一、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 {
// 設置屬性
@Test
public 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());
}
// 自定義轉換器
@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());
}
// 使用內置的轉換器
@Test
public 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());
}
}轉自:http://blog.csdn.net/xiazdong/article/details/7339687 本文由用戶 openkk 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!