package com.wzh.test.beanutils;
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;
//使用BeanUtils操作Bean屬性(第三方)
public class Demo1 {
@Test
public void test1() throws IllegalAccessException,
InvocationTargetException {
Person p = new Person();
BeanUtils.setProperty(p, "name", "victor");
System.out.println(p.getName());
}
@Test
public void test2() throws IllegalAccessException,
InvocationTargetException {
Person p = new Person();
// 自動將String轉為int 支持8種基本數據類型
BeanUtils.setProperty(p, "age", "23");
// 默認不支持時間轉換
BeanUtils.setProperty(p, "Birthday", "2012-3-1");
System.out.println(p.getAge());
System.out.println(p.getBirthday());
}
@Test
public void test3() throws IllegalAccessException,
InvocationTargetException {
// 為了讓日期賦到Bean的Birthday屬性上,我們給BeanUtils注冊一個日期轉換器(敲入代碼未起作用,需檢查)
// 方法1.
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object value) {
if (value == null)
return null;
if (!(value instanceof String)) {
System.out.println("不是日期類型");
throw new ConversionException("不是日期類型");
}
String str = (String) value;
if (str.trim().equals(str)) {
return null;
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);// 異常鏈不能斷
}
}
}, Date.class);
// ConvertUtils.register(new DateLocaleConverter(), Date.class);
Person p = new Person();
// 自動將String轉為int 支持8種基本數據類型
BeanUtils.setProperty(p, "birthday", "2012-12-12");
System.out.println(p.getBirthday());
}
@Test
public void test4() throws IllegalAccessException,
InvocationTargetException {
Map map = new HashMap();
map.put("name", "aa");
map.put("birthday", "2012-1-1");
ConvertUtils.register(new DateLocaleConverter(), Date.class);
Person p = new Person();
// 自動將String轉為int 支持8種基本數據類型
BeanUtils.populate(p, map);//用Map集合中的值填充到Bean的屬性
System.out.println(p.getBirthday());
}
}
package com.wzh.test.beanutils;
import java.util.Date;
public class Person {
public Person() {
super();
// TODO Auto-generated constructor stub
}
private String name;
private String age;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}