利用发射将Java对象的属性值以属性名称为键,存储到Map中的简单实现。包括自身属性及从父类继承得到的属性。Java类型的getField[s]方法只能获取public 类型的属性,getDeclaredFields则能获取所有声明的属性,同时,如果类的可见性非公有,则Field的get(Object)方法将取不到具体的属性值。
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
package com.wood.util;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
*
* @ClassName: BeanToMapUtils
* @Description: TODO
* @author wood
* @date 2014-10-31 下午09:52:41
*
*/
public class BeanToMapUtils {
/**
* getFileds获取所有public 属性<br/>
* getDeclaredFields 获取所有声明的属性<br/>
* @param bean
* @return 将某个类及其继承属性全部添加到Map中
*/
public static Map<String,Object> beanToMap(Object bean){
Map<String,Object> result = new HashMap<String,Object>();
if (bean== null ){
return result;
}
Field[] fields = bean.getClass().getDeclaredFields();
if (fields== null ||fields.length== 0 ){
return result;
}
for (Field field:fields){
//重置属性可见(而且一般属性都是私有的),否则操作无效
boolean accessible = field.isAccessible();
if (!accessible){
field.setAccessible( true );
}
//获取属性名称及值存入Map
String key = field.getName();
try {
result.put(key, field.get(bean));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//还原属性标识
field.setAccessible(accessible);
}
//获取父类属性
fields = bean.getClass().getSuperclass().getDeclaredFields();
if (fields== null ||fields.length== 0 ){
return result;
}
for (Field field:fields){
//重置属性可见(而且一般属性都是私有的),否则操作无效
boolean accessible = field.isAccessible();
if (!accessible){
field.setAccessible( true );
}
//获取属性名称及值存入Map
String key = field.getName();
try {
result.put(key, field.get(bean));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//还原属性标识
field.setAccessible(accessible);
}
return result;
}
public static void main(String[] args) {
Dog info = new Dog();
info.setCountry( "cc" );
info.setName( "Dog" );
info.setCategory( "gram" );
info.setOwner( "wang" );
System.out.println(beanToMap(info));
}
}
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/wojiushiwo945you/article/details/40710427