懒羊羊
2024-01-31 e57a8990ae56f657a59c435a0613c5f7a8728003
提交 | 用户 | 时间
e57a89 1 package com.jcdm.common.utils.reflect;
2
3 import java.lang.reflect.Field;
4 import java.lang.reflect.InvocationTargetException;
5 import java.lang.reflect.Method;
6 import java.lang.reflect.Modifier;
7 import java.lang.reflect.ParameterizedType;
8 import java.lang.reflect.Type;
9 import java.util.Date;
10 import org.apache.commons.lang3.StringUtils;
11 import org.apache.commons.lang3.Validate;
12 import org.apache.poi.ss.usermodel.DateUtil;
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
15 import com.jcdm.common.core.text.Convert;
16 import com.jcdm.common.utils.DateUtils;
17
18 /**
19  * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
20  * 
21  * @author jc
22  */
23 @SuppressWarnings("rawtypes")
24 public class ReflectUtils
25 {
26     private static final String SETTER_PREFIX = "set";
27
28     private static final String GETTER_PREFIX = "get";
29
30     private static final String CGLIB_CLASS_SEPARATOR = "$$";
31
32     private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);
33
34     /**
35      * 调用Getter方法.
36      * 支持多级,如:对象名.对象名.方法
37      */
38     @SuppressWarnings("unchecked")
39     public static <E> E invokeGetter(Object obj, String propertyName)
40     {
41         Object object = obj;
42         for (String name : StringUtils.split(propertyName, "."))
43         {
44             String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
45             object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
46         }
47         return (E) object;
48     }
49
50     /**
51      * 调用Setter方法, 仅匹配方法名。
52      * 支持多级,如:对象名.对象名.方法
53      */
54     public static <E> void invokeSetter(Object obj, String propertyName, E value)
55     {
56         Object object = obj;
57         String[] names = StringUtils.split(propertyName, ".");
58         for (int i = 0; i < names.length; i++)
59         {
60             if (i < names.length - 1)
61             {
62                 String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
63                 object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
64             }
65             else
66             {
67                 String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
68                 invokeMethodByName(object, setterMethodName, new Object[] { value });
69             }
70         }
71     }
72
73     /**
74      * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
75      */
76     @SuppressWarnings("unchecked")
77     public static <E> E getFieldValue(final Object obj, final String fieldName)
78     {
79         Field field = getAccessibleField(obj, fieldName);
80         if (field == null)
81         {
82             logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
83             return null;
84         }
85         E result = null;
86         try
87         {
88             result = (E) field.get(obj);
89         }
90         catch (IllegalAccessException e)
91         {
92             logger.error("不可能抛出的异常{}", e.getMessage());
93         }
94         return result;
95     }
96
97     /**
98      * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
99      */
100     public static <E> void setFieldValue(final Object obj, final String fieldName, final E value)
101     {
102         Field field = getAccessibleField(obj, fieldName);
103         if (field == null)
104         {
105             // throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
106             logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
107             return;
108         }
109         try
110         {
111             field.set(obj, value);
112         }
113         catch (IllegalAccessException e)
114         {
115             logger.error("不可能抛出的异常: {}", e.getMessage());
116         }
117     }
118
119     /**
120      * 直接调用对象方法, 无视private/protected修饰符.
121      * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用.
122      * 同时匹配方法名+参数类型,
123      */
124     @SuppressWarnings("unchecked")
125     public static <E> E invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
126             final Object[] args)
127     {
128         if (obj == null || methodName == null)
129         {
130             return null;
131         }
132         Method method = getAccessibleMethod(obj, methodName, parameterTypes);
133         if (method == null)
134         {
135             logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
136             return null;
137         }
138         try
139         {
140             return (E) method.invoke(obj, args);
141         }
142         catch (Exception e)
143         {
144             String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
145             throw convertReflectionExceptionToUnchecked(msg, e);
146         }
147     }
148
149     /**
150      * 直接调用对象方法, 无视private/protected修饰符,
151      * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
152      * 只匹配函数名,如果有多个同名函数调用第一个。
153      */
154     @SuppressWarnings("unchecked")
155     public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args)
156     {
157         Method method = getAccessibleMethodByName(obj, methodName, args.length);
158         if (method == null)
159         {
160             // 如果为空不报错,直接返回空。
161             logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
162             return null;
163         }
164         try
165         {
166             // 类型转换(将参数数据类型转换为目标方法参数类型)
167             Class<?>[] cs = method.getParameterTypes();
168             for (int i = 0; i < cs.length; i++)
169             {
170                 if (args[i] != null && !args[i].getClass().equals(cs[i]))
171                 {
172                     if (cs[i] == String.class)
173                     {
174                         args[i] = Convert.toStr(args[i]);
175                         if (StringUtils.endsWith((String) args[i], ".0"))
176                         {
177                             args[i] = StringUtils.substringBefore((String) args[i], ".0");
178                         }
179                     }
180                     else if (cs[i] == Integer.class)
181                     {
182                         args[i] = Convert.toInt(args[i]);
183                     }
184                     else if (cs[i] == Long.class)
185                     {
186                         args[i] = Convert.toLong(args[i]);
187                     }
188                     else if (cs[i] == Double.class)
189                     {
190                         args[i] = Convert.toDouble(args[i]);
191                     }
192                     else if (cs[i] == Float.class)
193                     {
194                         args[i] = Convert.toFloat(args[i]);
195                     }
196                     else if (cs[i] == Date.class)
197                     {
198                         if (args[i] instanceof String)
199                         {
200                             args[i] = DateUtils.parseDate(args[i]);
201                         }
202                         else
203                         {
204                             args[i] = DateUtil.getJavaDate((Double) args[i]);
205                         }
206                     }
207                     else if (cs[i] == boolean.class || cs[i] == Boolean.class)
208                     {
209                         args[i] = Convert.toBool(args[i]);
210                     }
211                 }
212             }
213             return (E) method.invoke(obj, args);
214         }
215         catch (Exception e)
216         {
217             String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
218             throw convertReflectionExceptionToUnchecked(msg, e);
219         }
220     }
221
222     /**
223      * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
224      * 如向上转型到Object仍无法找到, 返回null.
225      */
226     public static Field getAccessibleField(final Object obj, final String fieldName)
227     {
228         // 为空不报错。直接返回 null
229         if (obj == null)
230         {
231             return null;
232         }
233         Validate.notBlank(fieldName, "fieldName can't be blank");
234         for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass())
235         {
236             try
237             {
238                 Field field = superClass.getDeclaredField(fieldName);
239                 makeAccessible(field);
240                 return field;
241             }
242             catch (NoSuchFieldException e)
243             {
244                 continue;
245             }
246         }
247         return null;
248     }
249
250     /**
251      * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
252      * 如向上转型到Object仍无法找到, 返回null.
253      * 匹配函数名+参数类型。
254      * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
255      */
256     public static Method getAccessibleMethod(final Object obj, final String methodName,
257             final Class<?>... parameterTypes)
258     {
259         // 为空不报错。直接返回 null
260         if (obj == null)
261         {
262             return null;
263         }
264         Validate.notBlank(methodName, "methodName can't be blank");
265         for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass())
266         {
267             try
268             {
269                 Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
270                 makeAccessible(method);
271                 return method;
272             }
273             catch (NoSuchMethodException e)
274             {
275                 continue;
276             }
277         }
278         return null;
279     }
280
281     /**
282      * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
283      * 如向上转型到Object仍无法找到, 返回null.
284      * 只匹配函数名。
285      * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
286      */
287     public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum)
288     {
289         // 为空不报错。直接返回 null
290         if (obj == null)
291         {
292             return null;
293         }
294         Validate.notBlank(methodName, "methodName can't be blank");
295         for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass())
296         {
297             Method[] methods = searchType.getDeclaredMethods();
298             for (Method method : methods)
299             {
300                 if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum)
301                 {
302                     makeAccessible(method);
303                     return method;
304                 }
305             }
306         }
307         return null;
308     }
309
310     /**
311      * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
312      */
313     public static void makeAccessible(Method method)
314     {
315         if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
316                 && !method.isAccessible())
317         {
318             method.setAccessible(true);
319         }
320     }
321
322     /**
323      * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
324      */
325     public static void makeAccessible(Field field)
326     {
327         if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
328                 || Modifier.isFinal(field.getModifiers())) && !field.isAccessible())
329         {
330             field.setAccessible(true);
331         }
332     }
333
334     /**
335      * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
336      * 如无法找到, 返回Object.class.
337      */
338     @SuppressWarnings("unchecked")
339     public static <T> Class<T> getClassGenricType(final Class clazz)
340     {
341         return getClassGenricType(clazz, 0);
342     }
343
344     /**
345      * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
346      * 如无法找到, 返回Object.class.
347      */
348     public static Class getClassGenricType(final Class clazz, final int index)
349     {
350         Type genType = clazz.getGenericSuperclass();
351
352         if (!(genType instanceof ParameterizedType))
353         {
354             logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType");
355             return Object.class;
356         }
357
358         Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
359
360         if (index >= params.length || index < 0)
361         {
362             logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
363                     + params.length);
364             return Object.class;
365         }
366         if (!(params[index] instanceof Class))
367         {
368             logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
369             return Object.class;
370         }
371
372         return (Class) params[index];
373     }
374
375     public static Class<?> getUserClass(Object instance)
376     {
377         if (instance == null)
378         {
379             throw new RuntimeException("Instance must not be null");
380         }
381         Class clazz = instance.getClass();
382         if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR))
383         {
384             Class<?> superClass = clazz.getSuperclass();
385             if (superClass != null && !Object.class.equals(superClass))
386             {
387                 return superClass;
388             }
389         }
390         return clazz;
391
392     }
393
394     /**
395      * 将反射时的checked exception转换为unchecked exception.
396      */
397     public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e)
398     {
399         if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
400                 || e instanceof NoSuchMethodException)
401         {
402             return new IllegalArgumentException(msg, e);
403         }
404         else if (e instanceof InvocationTargetException)
405         {
406             return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException());
407         }
408         return new RuntimeException(msg, e);
409     }
410 }