ReportRelatedUtils.java
2.93 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package com.bsth.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.apache.poi.ss.formula.functions.T;
import com.bsth.entity.Line;
public class ReportRelatedUtils {
public static void main(String[] args) {
try {
ReportRelatedUtils test = new ReportRelatedUtils();
Line line = new Line();
line.setId(10);
line.setName("abc");
test.getValue(line, "name");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过字段名取到对象中该字段的相应值
*
* @param t
* 对象
* @param fieldName
* 字段名
* @return
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
* @throws NoSuchFieldException
*/
public <T> Object getValue(T t, String fieldName)
throws ClassNotFoundException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException,
NoSuchFieldException {
Object value = "";
String tmpFieldName = firstCharToUpperCase(fieldName);
Method method = null;
try {
method = t.getClass().getMethod("get" + tmpFieldName);
value = method.invoke(t);
} catch (NoSuchMethodException e) {
if(method == null){
method = t.getClass().getMethod("get" + tmpFieldName);
}
value = method.invoke(t);
return value;
}
return value;
}
/**
* 通过字段名取到对象中该字段的相应值
*
* @param t
* 对象
* @param fieldName
* 字段名
* @return
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
* @throws NoSuchFieldException
*/
public Map<String,Object> getMapValue(Object t)
throws ClassNotFoundException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException,
NoSuchFieldException {
Map<String,Object> map = new HashMap<String, Object>();
Object value = "";
Field[] fields = t.getClass().getDeclaredFields();
for(Field field:fields){
String fieldName = field.getName();
String tmpFieldName = firstCharToUpperCase(fieldName);
Method method = null;
try {
method = t.getClass().getMethod("get" + tmpFieldName);
value = method.invoke(t)==null?"":method.invoke(t);
} catch (NoSuchMethodException e) {
value = "";
}
map.put(fieldName, value);
}
return map;
}
/**
* 首字母大写
*
* @param source
* 源字符串
* @return
*/
private String firstCharToUpperCase(String source) {
char[] arr = source.toCharArray();
if (arr[1] >= 'A' && arr[1] <= 'Z') {
return source;
}else{
if (arr[0] >= 'a' && arr[0] <= 'z') {
arr[0] -= 'a' - 'A';
}
}
return new String(arr);
}
}