BeanMapUtil.java
2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.bjivt.base.bean;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
public class BeanMapUtil
{
public static Object Map2Bean(Class type, Map map)
throws IntrospectionException, IllegalAccessException, InstantiationException, InvocationTargetException
{
ConvertUtils.register(new DateConvert(), Date.class);
BeanInfo beanInfo = Introspector.getBeanInfo(type);
Object obj = type.newInstance();
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!(map.containsKey(propertyName.toUpperCase()))) continue;
try {
Object value = map.get(propertyName.toUpperCase());
BeanUtils.setProperty(obj, propertyName, value);
}
catch (Exception e) {
}
}
return obj;
}
public static Map bean2Map(Object bean)
throws IntrospectionException, IllegalAccessException, InvocationTargetException
{
Class type = bean.getClass();
Map returnMap = new HashMap();
BeanInfo beanInfo = Introspector.getBeanInfo(type);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
if (!(propertyName.equals("class"))) {
Method readMethod = descriptor.getReadMethod();
Object result = readMethod.invoke(bean, new Object[0]);
if (result != null)
returnMap.put(propertyName, result);
else {
returnMap.put(propertyName, "");
}
}
}
return returnMap;
}
}