利用反射的方法将Object对象转换为XML字符串:
根据类名反射得到其属性及属性值,属性为XML标签,属性值为XML标签值。
01
import
java.lang.reflect.Field;
02
import
java.lang.reflect.Method;
03
import
java.util.List;
04
05
public
class
ObjectToXml {
06
/**
09
* @param object
10
* <a href="http://home.51cto.com/index.php?s=/space/34010" target="_blank">@return</a> String
11
* <a href="http://home.51cto.com/index.php?s=/space/2305405" target="_blank">@throws</a> Exception
12
*/
13
public
static
String ObjecttoXML(Object object)
throws
Exception {
14
Class<?
extends
Object> classType = object.getClass();
15
//属性集合
16
Field[] fields = classType.getDeclaredFields();
17
String xml =
""
;
18
for
(Field field : fields) {
20
String stringLetter = fieldName.substring(
0
,
1
).toUpperCase();
21
// 获得object对象相应的get方法
22
String getName =
"get"
+ stringLetter + fieldName.substring(
1
);
24
Method getMethod = classType.getMethod(getName,
new
Class[] {});
26
Object getValue = getMethod.invoke(object,
new
Object[] {});
27
if
(
null
== getValue) {
28
getValue =
""
;
29
}
30
xml +=
"<"
+ fieldName +
">"
+ getValue +
"</"
+ fieldName +
">"
;
31
}
32
xml =
"<object>"
+ xml +
"</object>"
;
33
return
xml;
34
}
35
36
/**
39
* @param objectList
40
* <a href="http://home.51cto.com/index.php?s=/space/34010" target="_blank">@return</a> String
41
* <a href="http://home.51cto.com/index.php?s=/space/2305405" target="_blank">@throws</a> Exception
42
*/
43
public
static
String ObjecttoXML(List<Object> objectList)
throws
Exception {
44
String xml =
""
;
45
xml +=
"<objects>"
;
46
for
(
int
i =
0
; i < objectList.size(); i++) {
47
Object object = objectList.get(i);
48
Class<?
extends
Object> classType = object.getClass();
49
Field[] fields = classType.getDeclaredFields();
50
xml +=
"<object>"
;
51
for
(Field field : fields) {
52
String fieldName = field.getName();
53
String stringLetter = fieldName.substring(
0
,
1
).toUpperCase();
54
String getName =
"get"
+ stringLetter + fieldName.substring(
1
);
55
Method getMethod = classType.getMethod(getName,
new
Class[] {});
56
Object getValue = getMethod.invoke(object,
new
Object[] {});
57
if
(
null
== getValue) {
58
getValue =
""
;
59
}
60
xml +=
"<"
+ fieldName +
">"
+ getValue +
"</"
+ fieldName +
">"
;
61
}
62
xml +=
"</object>"
;
63
}
64
xml +=
"</objects>"
;
65
return
xml;
66
}
67
}