ReportRelatedUtils.java
1.75 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
package com.bsth.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
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 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);
}
}