`

java反射工具类

 
阅读更多
  1. import java.lang.reflect.Field;  
  2. import java.lang.reflect.InvocationTargetException;  
  3. import java.lang.reflect.Method;  
  4. import java.lang.reflect.Modifier;  
  5. import java.lang.reflect.ParameterizedType;  
  6. import java.lang.reflect.Type;  
  7. import java.util.ArrayList;  
  8. import java.util.Collection;  
  9. import java.util.Date;  
  10. import java.util.List;  
  11.   
  12. import org.apache.commons.beanutils.ConvertUtils;  
  13. import org.apache.commons.beanutils.PropertyUtils;  
  14. import org.apache.commons.beanutils.converters.DateConverter;  
  15. import org.apache.commons.lang.StringUtils;  
  16. import org.slf4j.Logger;  
  17. import org.slf4j.LoggerFactory;  
  18. import org.springframework.util.Assert;  
  19.   
  20. /** 
  21.  * 反射工具类. 
  22.  *  
  23.  * 提供访问私有变量,获取泛型类型Class, 提取集合中元素的属性, 转换字符串到对象等Util函数. 
  24.  *  
  25.  */  
  26. public class ReflectionUtils {  
  27.   
  28.     private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);  
  29.   
  30.     static {  
  31.         DateConverter dc = new DateConverter();  
  32.         dc.setUseLocaleFormat(true);  
  33.         dc.setPatterns(new String[] { "yyyy-MM-dd""yyyy-MM-dd HH:mm:ss" });  
  34.         ConvertUtils.register(dc, Date.class);  
  35.     }  
  36.   
  37.     /** 
  38.      * 调用Getter方法. 
  39.      */  
  40.     public static Object invokeGetterMethod(Object target, String propertyName) {  
  41.         String getterMethodName = "get" + StringUtils.capitalize(propertyName);  
  42.         return invokeMethod(target, getterMethodName, new Class[] {}, new Object[] {});  
  43.     }  
  44.   
  45.     /** 
  46.      * 调用Setter方法.使用value的Class来查找Setter方法. 
  47.      */  
  48.     public static void invokeSetterMethod(Object target, String propertyName, Object value) {  
  49.         invokeSetterMethod(target, propertyName, value, null);  
  50.     }  
  51.   
  52.     /** 
  53.      * 调用Setter方法. 
  54.      *  
  55.      * @param propertyType 用于查找Setter方法,为空时使用value的Class替代. 
  56.      */  
  57.     public static void invokeSetterMethod(Object target, String propertyName, Object value, Class<?> propertyType) {  
  58.         Class<?> type = propertyType != null ? propertyType : value.getClass();  
  59.         String setterMethodName = "set" + StringUtils.capitalize(propertyName);  
  60.         invokeMethod(target, setterMethodName, new Class[] { type }, new Object[] { value });  
  61.     }  
  62.   
  63.     /** 
  64.      * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. 
  65.      */  
  66.     public static Object getFieldValue(final Object object, final String fieldName) {  
  67.         Field field = getDeclaredField(object, fieldName);  
  68.   
  69.         if (field == null) {  
  70.             throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");  
  71.         }  
  72.   
  73.         makeAccessible(field);  
  74.   
  75.         Object result = null;  
  76.         try {  
  77.             result = field.get(object);  
  78.         } catch (IllegalAccessException e) {  
  79.             logger.error("不可能抛出的异常{}", e.getMessage());  
  80.         }  
  81.         return result;  
  82.     }  
  83.   
  84.     /** 
  85.      * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. 
  86.      */  
  87.     public static void setFieldValue(final Object object, final String fieldName, final Object value) {  
  88.         Field field = getDeclaredField(object, fieldName);  
  89.   
  90.         if (field == null) {  
  91.             throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");  
  92.         }  
  93.   
  94.         makeAccessible(field);  
  95.   
  96.         try {  
  97.             field.set(object, value);  
  98.         } catch (IllegalAccessException e) {  
  99.             logger.error("不可能抛出的异常:{}", e.getMessage());  
  100.         }  
  101.     }  
  102.   
  103.     /** 
  104.      * 直接调用对象方法, 无视private/protected修饰符. 
  105.      */  
  106.     public static Object invokeMethod(final Object object, final String methodName, final Class<?>[] parameterTypes,  
  107.             final Object[] parameters) {  
  108.         Method method = getDeclaredMethod(object, methodName, parameterTypes);  
  109.         if (method == null) {  
  110.             throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");  
  111.         }  
  112.   
  113.         method.setAccessible(true);  
  114.   
  115.         try {  
  116.             return method.invoke(object, parameters);  
  117.         } catch (Exception e) {  
  118.             throw convertReflectionExceptionToUnchecked(e);  
  119.         }  
  120.     }  
  121.   
  122.     /** 
  123.      * 循环向上转型, 获取对象的DeclaredField. 
  124.      *  
  125.      * 如向上转型到Object仍无法找到, 返回null. 
  126.      */  
  127.     protected static Field getDeclaredField(final Object object, final String fieldName) {  
  128.         Assert.notNull(object, "object不能为空");  
  129.         Assert.hasText(fieldName, "fieldName");  
  130.         for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass  
  131.                 .getSuperclass()) {  
  132.             try {  
  133.                 return superClass.getDeclaredField(fieldName);  
  134.             } catch (NoSuchFieldException e) {//NOSONAR  
  135.                 // Field不在当前类定义,继续向上转型  
  136.             }  
  137.         }  
  138.         return null;  
  139.     }  
  140.   
  141.     /** 
  142.      * 强行设置Field可访问. 
  143.      */  
  144.     protected static void makeAccessible(final Field field) {  
  145.         if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {  
  146.             field.setAccessible(true);  
  147.         }  
  148.     }  
  149.   
  150.     /** 
  151.      * 循环向上转型, 获取对象的DeclaredMethod. 
  152.      *  
  153.      * 如向上转型到Object仍无法找到, 返回null. 
  154.      */  
  155.     protected static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) {  
  156.         Assert.notNull(object, "object不能为空");  
  157.   
  158.         for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass  
  159.                 .getSuperclass()) {  
  160.             try {  
  161.                 return superClass.getDeclaredMethod(methodName, parameterTypes);  
  162.             } catch (NoSuchMethodException e) {//NOSONAR  
  163.                 // Method不在当前类定义,继续向上转型  
  164.             }  
  165.         }  
  166.         return null;  
  167.     }  
  168.   
  169.     /** 
  170.      * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 
  171.      * 如无法找到, 返回Object.class. 
  172.      * eg. 
  173.      * public UserDao extends HibernateDao<User> 
  174.      * 
  175.      * @param clazz The class to introspect 
  176.      * @return the first generic declaration, or Object.class if cannot be determined 
  177.      */  
  178.     @SuppressWarnings("unchecked")  
  179.     public static <T> Class<T> getSuperClassGenricType(final Class clazz) {  
  180.         return getSuperClassGenricType(clazz, 0);  
  181.     }  
  182.   
  183.     /** 
  184.      * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 
  185.      * 如无法找到, 返回Object.class. 
  186.      *  
  187.      * 如public UserDao extends HibernateDao<User,Long> 
  188.      * 
  189.      * @param clazz clazz The class to introspect 
  190.      * @param index the Index of the generic ddeclaration,start from 0. 
  191.      * @return the index generic declaration, or Object.class if cannot be determined 
  192.      */  
  193.     @SuppressWarnings("unchecked")  
  194.     public static Class getSuperClassGenricType(final Class clazz, final int index) {  
  195.         Type genType = clazz.getGenericSuperclass();  
  196.   
  197.         if (!(genType instanceof ParameterizedType)) {  
  198.             logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");  
  199.             return Object.class;  
  200.         }  
  201.   
  202.         Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
  203.   
  204.         if (index >= params.length || index < 0) {  
  205.             logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "  
  206.                     + params.length);  
  207.             return Object.class;  
  208.         }  
  209.         if (!(params[index] instanceof Class)) {  
  210.             logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");  
  211.             return Object.class;  
  212.         }  
  213.   
  214.         return (Class) params[index];  
  215.     }  
  216.   
  217.     /** 
  218.      * 提取集合中的对象的属性(通过getter函数), 组合成List. 
  219.      *  
  220.      * @param collection 来源集合. 
  221.      * @param propertyName 要提取的属性名. 
  222.      */  
  223.     @SuppressWarnings("unchecked")  
  224.     public static List convertElementPropertyToList(final Collection collection, final String propertyName) {  
  225.         List list = new ArrayList();  
  226.   
  227.         try {  
  228.             for (Object obj : collection) {  
  229.                 list.add(PropertyUtils.getProperty(obj, propertyName));  
  230.             }  
  231.         } catch (Exception e) {  
  232.             throw convertReflectionExceptionToUnchecked(e);  
  233.         }  
  234.   
  235.         return list;  
  236.     }  
  237.   
  238.     /** 
  239.      * 提取集合中的对象的属性(通过getter函数), 组合成由分割符分隔的字符串. 
  240.      *  
  241.      * @param collection 来源集合. 
  242.      * @param propertyName 要提取的属性名. 
  243.      * @param separator 分隔符. 
  244.      */  
  245.     @SuppressWarnings("unchecked")  
  246.     public static String convertElementPropertyToString(final Collection collection, final String propertyName,  
  247.             final String separator) {  
  248.         List list = convertElementPropertyToList(collection, propertyName);  
  249.         return StringUtils.join(list, separator);  
  250.     }  
  251.   
  252.     /** 
  253.      * 转换字符串到相应类型. 
  254.      *  
  255.      * @param value 待转换的字符串 
  256.      * @param toType 转换目标类型 
  257.      */  
  258.     @SuppressWarnings("unchecked")  
  259.     public static <T> T convertStringToObject(String value, Class<T> toType) {  
  260.         try {  
  261.             return (T) ConvertUtils.convert(value, toType);  
  262.         } catch (Exception e) {  
  263.             throw convertReflectionExceptionToUnchecked(e);  
  264.         }  
  265.     }  
  266.   
  267.     /** 
  268.      * 将反射时的checked exception转换为unchecked exception. 
  269.      */  
  270.     public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {  
  271.         return convertReflectionExceptionToUnchecked(null, e);  
  272.     }  
  273.   
  274.     public static RuntimeException convertReflectionExceptionToUnchecked(String desc, Exception e) {  
  275.         desc = (desc == null) ? "Unexpected Checked Exception." : desc;  
  276.         if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException  
  277.                 || e instanceof NoSuchMethodException) {  
  278.             return new IllegalArgumentException(desc, e);  
  279.         } else if (e instanceof InvocationTargetException) {  
  280.             return new RuntimeException(desc, ((InvocationTargetException) e).getTargetException());  
  281.         } else if (e instanceof RuntimeException) {  
  282.             return (RuntimeException) e;  
  283.         }  
  284.         return new RuntimeException(desc, e);  
  285.     }  
  286.   
  287.     public static final <T> T getNewInstance(Class<T> cls) {  
  288.         try {  
  289.             return cls.newInstance();  
  290.         } catch (InstantiationException e) {  
  291.             e.printStackTrace();  
  292.         } catch (IllegalAccessException e) {  
  293.             e.printStackTrace();  
  294.         }  
  295.         return null;  
  296.     }  
  297. }  
分享到:
评论
1 楼 xchd 2014-10-25  
支持这种情况吗
  public List<Person> getPerson() {
        return persons;
    }

相关推荐

Global site tag (gtag.js) - Google Analytics