BeanUtils是apache的開發庫;html
爲了使用BeanUtils,須要導入java
(1)common-logging-1.1.1.jarapache
(2)common-beanutils.jaride
01 |
package org.xiazdong.beanutils; |
02 |
03 |
import java.text.ParseException; |
04 |
import java.text.SimpleDateFormat; |
05 |
import java.util.Date; |
06 |
import java.util.HashMap; |
07 |
import java.util.Map; |
08 |
09 |
import org.apache.commons.beanutils.BeanUtils; |
10 |
import org.apache.commons.beanutils.ConversionException; |
11 |
import org.apache.commons.beanutils.ConvertUtils; |
12 |
import org.apache.commons.beanutils.Converter; |
13 |
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter; |
14 |
import org.junit.Test; |
15 |
import org.xiazdong.Person; |
16 |
17 |
public class Demo01 { |
18 |
19 |
// 設置屬性 |
20 |
@Test |
21 |
public void test1() throws Exception { |
22 |
Person p = new Person(); |
23 |
BeanUtils.setProperty(p, "name" , "xiazdong" ); |
24 |
BeanUtils.setProperty(p, "age" , 20 ); |
25 |
System.out.println(p.getName()); |
26 |
System.out.println(p.getAge()); |
27 |
} |
28 |
29 |
// 自定義轉換器 |
30 |
@Test |
31 |
public void test2() throws Exception { |
32 |
Person p = new Person(); |
33 |
ConvertUtils.register( new Converter() { |
34 |
35 |
@Override |
36 |
public Object convert(Class type, Object value) { |
37 |
if (value == null ) { |
38 |
return null ; |
39 |
} |
40 |
if (!(value instanceof String)) { |
41 |
throw new ConversionException( "conversion error" ); |
42 |
} |
43 |
String str = (String) value; |
44 |
if (str.trim().equals( "" )) { |
45 |
return null ; |
46 |
} |
47 |
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" ); |
48 |
try { |
49 |
return sdf.parse(str); |
50 |
} catch (ParseException e) { |
51 |
throw new RuntimeException(e); |
52 |
} |
53 |
54 |
} |
55 |
56 |
}, Date. class ); |
57 |
BeanUtils.setProperty(p, "birth" , "2011-10-10" ); |
58 |
System.out.println(p.getBirth().toLocaleString()); |
59 |
} |
60 |
61 |
// 使用內置的轉換器 |
62 |
@Test |
63 |
public void test3() throws Exception { |
64 |
Person p = new Person(); |
65 |
ConvertUtils.register( new DateLocaleConverter(), Date. class ); |
66 |
BeanUtils.setProperty(p, "birth" , "2011-10-10" ); |
67 |
System.out.println(p.getBirth().toLocaleString()); |
68 |
} |
69 |
70 |
// 使用內置的轉換器 |
71 |
@Test |
72 |
public void test4() throws Exception { |
73 |
Map map = new HashMap(); |
74 |
map.put( "name" , "xiazdong" ); |
75 |
map.put( "age" , "20" ); |
76 |
map.put( "birth" , "2010-10-10" ); |
77 |
ConvertUtils.register( new DateLocaleConverter(), Date. class ); |
78 |
Person p = new Person(); |
79 |
BeanUtils.populate(p, map); |
80 |
System.out.println(p.getAge()); |
81 |
System.out.println(p.getBirth()); |
82 |
} |
83 |
} |