Java 提供 java.beans.Introspector 類,幫助我們分析 JavaBean 類當中 有哪些屬性,通過它可以方便的對 JavaBean 對象屬性進行取值和賦值操作。下 面是一個例子,根據 Map 對象中的內容創建 JavaBean 對象。
01.import java.beans.BeanInfo;
02.import java.beans.IntrospectionException;
03.import java.beans.Introspector;
04.import java.beans.PropertyDescriptor;
05.import java.util.HashMap;
06.import java.util.Map;
07.import java.lang.reflect.InvocationTargetException;
08.
09.public class MapToBean {
10.
11. public static void main(String[] args) throws Exception {
12. Map<Object, Object> map = new HashMap<Object,
Object>();
13. map.put("name", "張三");
14. map.put("age", 30);
15. Person p = convertMap(Person.class, map);
16. System.out.println(p.getName() + ", " + p.getAge
());
17. }
18.
19. /**
20. * 將一個 Map 對象轉化為一個 JavaBean
21. *
22. * @param type 要轉化的類型
23. * @param map 包含屬性值的 map
24. *
25. * @return 轉化出來的 JavaBean 對象
26. *
27. * @throws IntrospectionException 如果分析類屬性失敗
28. * @throws IllegalAccessException 如果實例化 JavaBean 失敗
29. * @throws InstantiationException 如果實例化 JavaBean 失敗
30. * @throws InvocationTargetException 如果調用屬性的 setter 方法
失敗
31. */
32. private static <T> T convertMap(Class<T> type,
Map<Object, Object> map)
33. throws IntrospectionException, IllegalAccessException,
34. InstantiationException, InvocationTargetException {
35. BeanInfo beanInfo = Introspector.getBeanInfo(type); // 獲取
類屬性
36. T t = type.newInstance(); // 創建 JavaBean 對象
37.
38. // 給 JavaBean 對象的屬性賦值
39. for (PropertyDescriptor descriptor :
beanInfo.getPropertyDescriptors()) {
40. String propertyName = descriptor.getName();
41. if (map.containsKey(propertyName)) {
42. // 下面一句可以 try 起來,這樣當一個屬性賦值失敗的
時候就不會影響其他屬性賦值。
43. descriptor.getWriteMethod().invoke(t, map.get
(propertyName));
44. }
45. }
46. return t;
47. }
48.}
49.
50.class Person {
51.
52. private String name;
53.
54. private int age;
55.
56. public String getName() {
57. return name;
58. }
59.
60. public void setName(String name) {
61. this.name = name;
62. }
63.
64. public int getAge() {
65. return age;
66. }
67.
68. public void setAge(int age) {
69. this.age = age;
70. }
71.}