最近项目里需要一个工具类,它的功能是传入一个Map后可以返回一个JavaBean对象。很喜欢写这样的Java服务,首先我想到的是要通过Java 的反射去实现匿名类的方法调用,这样才可以把Map里的值set 到JavaBean里。其实这里用Java的自省会更方便,下面两个方法就是一个通过反射,一个通过自省来实现本功能。
1:JavaBean类
1 package cn.com.bean;
2 public class Person {
3 private int id;
4 private String name;
5 private String birthday;
6 private String type;
7 private String hobby;
8 public int getId() {
9 return id;
10 }
11 public void setId(int id) {
12 this.id = id;
13 }
14 public String getName() {
15 return name;
16 }
17 public void setName(String name) {
18 this.name = name;
19 }
20 public String getBirthday() {
21 return birthday;
22 }
23 public void setBirthday(String birthday) {
24 this.birthday = birthday;
25 }
26 public String getType() {
27 return type;
28 }
29 public void setType(String type) {
30 this.type = type;
31 }
32 public String getHobby() {
33 return hobby;
34 }
35 public void setHobby(String hobby) {
36 this.hobby = hobby;
37 }
38 @Override
39 public String toString(){
40 StringBuffer sb = new StringBuffer();
41 sb.append("{");
42 sb.append("'id':'"+getId()+"',");
43 sb.append("'name':'"+getName()+"',");
44 sb.append("'type':'"+getType()+"',");
45 sb.append("'birthday':'"+getBirthday()+"',");
46 sb.append("'hobby':'"+getHobby()+"'");
47 sb.append("}");
48 return sb.toString();
49 }
50 }
2 工具类:
51 package cn.com.util;
52 import java.beans.BeanInfo;
53 import java.beans.IntrospectionException;
54 import java.beans.Introspector;
55 import java.beans.PropertyDescriptor;
56 import java.lang.reflect.Field;
57 import java.lang.reflect.InvocationTargetException;
58 import java.lang.reflect.Method;
59 import java.util.Map;
60 import java.util.Set;
61 public class ConvertUtil {
62
63 /**
64 * 把一个Map转换成一个实体类JavaBean(通过反射机制实现)
65 * @param map
66 * @return
67 */ public Object convertMayToBean(Map map) throws InstantiationException, IllegalAccessException{
68 if(map==null || map.size()==0){
69 return null;
70 }
71 if(map.get("table-name")==null){
72 return null;
73 }
74 String beanName = new ReadUtil().readString((String)map.get("table-name"));
75 if(beanName==null || "".equals(beanName))
76 {
77 return null;
78 }
79 Class clazz = null;
80 try {
81 clazz= Class.forName(beanName);
82 } catch (ClassNotFoundException e) {
83 e.printStackTrace();
84 }
85 Object object = clazz.newInstance();
86
87 //获得对象的所有属性
88 Field[] fields=clazz.getDeclaredFields();
89 for(int i=0;i<fields.length;i++){
90 String key = fields[i].getName();
91 if(map.containsKey(key)){
92 String tempKey = key.substring(0,1).toUpperCase()+key.substring(1,
93 key.length());
94 try {
95 Method method = clazz.getMethod("set"+tempKey,new Class[] {fields[i].getType()});
96 Object args[] = new Object[1];
97 args[0] = map.get(key);
98 method.invoke(object,args);
99 } catch (SecurityException e) {
100 e.printStackTrace();
101 } catch (NoSuchMethodException e) {
102 e.printStackTrace();
103 }catch (IllegalArgumentException e) {
104 e.printStackTrace();
105 } catch (IllegalAccessException e) {
106 e.printStackTrace();
107 } catch (InvocationTargetException e) {
108 e.printStackTrace();
109 }
110 }
111 }
112 return object;
113 }
114
115 /**
116 * 下面通过内省实现
117 * @param map
118 * @return
119 */
120 public Object convertMap2Bean(Map<String, Object> map) throws IntrospectionException,
121 InstantiationException, IllegalAccessException, IllegalArgumentException,
122 InvocationTargetException, ClassNotFoundException{
123 if(map==null || map.size()==0){
124 return null;
125 }
126 if(map.get("table-name")==null){
127 return null;
128 }
129 String beanName = new ReadUtil().readString((String)map.get("table-name"));
130 if(beanName==null || "".equals(beanName))
131 {
132 return null;
133 }
134 Class c = Class.forName(beanName);
135 Object obj=c.newInstance();
136 BeanInfo beanInfo = Introspector.getBeanInfo(c);
137 PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
138 Set<String> keys=map.keySet();
139 for (String key : keys) {
140 for (PropertyDescriptor pd : pds) {
141 if(pd.getName().equals(key)){
142 pd.getWriteMethod().invoke(obj, map.get(key));
143 break;
144 }
145 }
146 }
147 return obj;
148 }
149 }
150
151
152 package cn.com.util;
153 import java.io.IOException;
154 import java.io.InputStream;
155 import java.util.HashMap;
156 import java.util.Map;
157 import java.util.Properties;
158 public class ReadUtil {
159 public String readString(String tableName){
160 InputStream in = ClassLoader.getSystemResourceAsStream("table-bean.properties");
161 Properties p = new Properties();
162 try {
163 p.load(in);
164 } catch (IOException e) {
165 e.printStackTrace();
166 }
167 return p.getProperty(tableName);
168 }
169 }
3 一个配置文件:table-bean.properties
t_person_info=cn.com.bean.Person
4 测试类
170 import java.beans.BeanInfo;
171 import java.beans.IntrospectionException;
172 import java.beans.Introspector;
173 import java.beans.PropertyDescriptor;
174 import java.lang.reflect.InvocationTargetException;
175 import java.util.HashMap;
176 import java.util.Map;
177 import cn.com.bean.Person;
178 import cn.com.util.ConvertUtil;
179 public class Test {
180
181 public static void main(String[] args) throws Exception {
182
183 Map map = new HashMap();
184 map.put("id", 1111);
185 map.put("name", "zhou yang");
186 map.put("birthday", "1989-11-10");
187 map.put("type", "1");
188 map.put("hobby", "reading");
189 map.put("table-name", "t_person_info");
190 ConvertUtil util = new ConvertUtil();
191 //Object object = util.convertMayToBean(map);
192 // System.out.println(object.toString());
193
194 Object object = util.convertMap2Bean(map);
195 System.out.println(object.toString());
196
197 new Test().testJavaBeanInfo();
198 }
199
200 //内省测试方法
201 public void testJavaBeanInfo() throws Exception{
202 Person p = new Person();
203 p.setBirthday("2011-10-20");
204 p.setId(007);
205 p.setName("吉它");
206 p.setType("2");
207 p.setHobby("弹吉它、看风景");
208
209 BeanInfo bean = Introspector.getBeanInfo(p.getClass(),Object.class);
210
211 PropertyDescriptor[] pds = bean.getPropertyDescriptors();
212 for(int i=0;i<pds.length;i++){
213 System.out.print("name: "+pds[i].getName()+" ");
214
215 /**
216 * 下面这句invok(p,null),传参数为p,正好是上面的Person对象实例
217 * 表示调的就是上面的p对象的读方法(即getXXX())
218 */
219 System.out.println(pds[i].getReadMethod().invoke(p,null));
220
221 }
222 }
223 }
JavaBean的内省就是对JavaBean中的属性和事件的一些处理方法,通过setName和getName去访问和设置name的值。Java中通过Introspector类的getBeanInfo(beanClass)静态方法,获得JavaBean的BeanInfo集合,再遍历BeanInfo集合来得到JavaBean的某一个属性的属性描述器(PropertyDescriptor),利用PropertyDescriptor得到JavaBean中属性的get和set方法。
前人总结,后人乘凉,但要有所思,才为已用。