-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathReflectionUtils.java
More file actions
300 lines (268 loc) · 8.15 KB
/
ReflectionUtils.java
File metadata and controls
300 lines (268 loc) · 8.15 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/**
* Copyright (c) 2005-2009 springside.org.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* $Id: ReflectionUtils.java 384 2009-08-28 14:50:14Z calvinxiu $
*/
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
/**
* 反射的Utils函数集合.
*
* 提供访问私有变量,获取泛型类型Class,提取集合中元素的属性等Utils函数.
*
* @author calvin
*/
public class ReflectionUtils {
private static Log logger = LogFactory.getLog(ReflectionUtils.class);
/**
* 直接读取对象属性值,无视private/protected修饰符,不经过getter函数.
*/
public static Object getFieldValue(final Object object,
final String fieldName) {
Field field = getDeclaredField(object, fieldName);
if (field == null)
throw new IllegalArgumentException("Could not find field ["
+ fieldName + "] on target [" + object + "]");
makeAccessible(field);
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常{}", e);
}
return result;
}
/**
* 直接设置对象属性值,无视private/protected修饰符,不经过setter函数.
*/
public static void setFieldValue(final Object object,
final String fieldName, final Object value) {
Field field = getDeclaredField(object, fieldName);
if (field == null)
throw new IllegalArgumentException("Could not find field ["
+ fieldName + "] on target [" + object + "]");
makeAccessible(field);
try {
field.set(object, value);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常:{}", e);
}
}
/**
* 直接调用对象方法,无视private/protected修饰符.
*/
public static Object invokeMethod(final Object object,
final String methodName, final Class<?>[] parameterTypes,
final Object[] parameters) throws InvocationTargetException {
Method method = getDeclaredMethod(object, methodName, parameterTypes);
if (method == null)
throw new IllegalArgumentException("Could not find method ["
+ methodName + "] on target [" + object + "]");
method.setAccessible(true);
try {
return method.invoke(object, parameters);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常:{}", e);
}
return null;
}
/**
* 循环向上转型,获取对象的DeclaredField.
*/
protected static Field getDeclaredField(final Object object,
final String fieldName) {
Assert.notNull(object, "object不能为空");
Assert.hasText(fieldName, "fieldName");
for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
.getSuperclass()) {
// System.out.println("class:" + superClass);
try {
return superClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
// Field不在当前类定义,继续向上转型
// e.printStackTrace();
// continue;
}
}
return null;
}
/**
* 循环向上转型,获取对象的DeclaredField.
*/
protected static void makeAccessible(final Field field) {
if (!Modifier.isPublic(field.getModifiers())
|| !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
field.setAccessible(true);
}
}
/**
* 循环向上转型,获取对象的DeclaredMethod.
*/
protected static Method getDeclaredMethod(Object object, String methodName,
Class<?>[] parameterTypes) {
Assert.notNull(object, "object不能为空");
for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
.getSuperclass()) {
try {
return superClass.getDeclaredMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
// Method不在当前类定义,继续向上转型
}
}
return null;
}
/**
* 通过反射,获得Class定义中声明的父类的泛型参数的类型. eg. public UserDao extends HibernateDao<User>
*
* @param clazz
* The class to introspect
* @return the first generic declaration, or Object.class if cannot be
* determined
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> getSuperClassGenricType(final Class clazz) {
return getSuperClassGenricType(clazz, 0);
}
/**
* 通过反射,获得定义Class时声明的父类的泛型参数的类型.
*
* 如public UserDao extends HibernateDao<User,Long>
*
* @param clazz
* clazz The class to introspect
* @param index
* the Index of the generic ddeclaration,start from 0.
* @return the index generic declaration, or Object.class if cannot be
* determined
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(final Class clazz,
final int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
logger.warn(clazz.getSimpleName()
+ "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
logger.warn("Index: " + index + ", Size of "
+ clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class)) {
logger
.warn(clazz.getSimpleName()
+ " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class) params[index];
}
/**
* 提取集合中的对象的属性(通过getter函数),组合成List.
*
* @param collection
* 来源集合.
* @param propertyName
* 要提取的属性名.
*/
@SuppressWarnings("unchecked")
public static List fetchElementPropertyToList(final Collection collection,
final String propertyName) {
List list = new ArrayList();
try {
for (Object obj : collection) {
list.add(PropertyUtils.getProperty(obj, propertyName));
}
} catch (Exception e) {
convertToUncheckedException(e);
}
return list;
}
/**
* 提取集合中的对象的属性(通过getter函数),组合成由分割符分隔的字符串.
*
* @param collection
* 来源集合.
* @param propertyName
* 要提取的属性名.
* @param separator
* 分隔符.
*/
@SuppressWarnings("unchecked")
public static String fetchElementPropertyToString(
final Collection collection, final String propertyName,
final String separator) {
List list = fetchElementPropertyToList(collection, propertyName);
return StringUtils.join(list, separator);
}
/**
* 转换字符串类型到clazz的property类型的值.
*
* @param value
* 待转换的字符串
* @param clazz
* 提供类型信息的Class
* @param propertyName
* 提供类型信息的Class的属性.
*/
public static Object convertValue(Object value, Class<?> toType) {
try {
DateConverter dc = new DateConverter();
dc.setUseLocaleFormat(true);
dc
.setPatterns(new String[] { "yyyy-MM-dd",
"yyyy-MM-dd HH:mm:ss" });
ConvertUtils.register(dc, Date.class);
return ConvertUtils.convert(value, toType);
} catch (Exception e) {
throw convertToUncheckedException(e);
}
}
/**
* 将反射时的checked exception转换为unchecked exception.
*/
public static IllegalArgumentException convertToUncheckedException(
Exception e) {
if (e instanceof IllegalAccessException
|| e instanceof IllegalArgumentException
|| e instanceof NoSuchMethodException)
return new IllegalArgumentException("Refelction Exception.", e);
else
return new IllegalArgumentException(e);
}
/**
* 判断beanClass是否注册了指定Annotation
*
* @return
*/
public static boolean isAnnotationPresent(String beanClass, Class annotation) {
ClassLoader classLoader = annotation.getClassLoader();
Class clz = null;
try {
clz = classLoader.loadClass(beanClass);
} catch (ClassNotFoundException e) {
logger.warn("无法找到类:" + beanClass);
return false;
}
return clz.isAnnotationPresent(annotation);
}
}