熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

實用的Java反射工具類

2013-11-23 19:21:38  來源: Java核心技術 

  反射的Utils函數集合

  提供訪問私有變量獲取泛型類型Class提取集合中元素的屬性等Utils函數

  package reflection

   import javalangreflectField import javalangreflectModifier import javalangreflectParameterizedType import javalangreflectType import javautilArrayList import javautilCollection import javautilList

   import monsbeanutilsPropertyUtils import monslangStringUtils import orgslfjLogger import orgslfjLoggerFactory import orgspringframeworkutilAssert

   /** * 反射的Utils函數集合 提供訪問私有變量獲取泛型類型Class提取集合中元素的屬性等Utils函數

   * * @author lei */ public class ReflectionUtils {

   private static Logger logger = LoggerFactorygetLogger(ReflectionUtilsclass)

   private ReflectionUtils() { }

   /** * 直接讀取對象屬性值無視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 = fieldget(object) } catch (IllegalAccessException e) { loggererror(不可能拋出的異常{} egetMessage()) } 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 { fieldset(object value) } catch (IllegalAccessException e) { loggererror(不可能拋出的異常{} egetMessage()) } }

   /** * 循環向上轉型獲取對象的DeclaredField */ protected static Field getDeclaredField(final Object object final String fieldName) { AssertnotNull(object object不能為空 return getDeclaredField(objectgetClass() fieldName) }

   /** * 循環向上轉型獲取類的DeclaredField */ @SuppressWarnings(unchecked

   protected static Field getDeclaredField(final Class clazz final String fieldName) { AssertnotNull(clazz clazz不能為空 AsserthasText(fieldName fieldName for (Class superClass = clazz superClass != Objectclass superClass = superClassgetSuperclass()) { try { return superClassgetDeclaredField(fieldName) } catch (NoSuchFieldException e) { // Field不在當前類定義繼續向上轉型 } } return null }

   /** * 強制轉換fileld可訪問

   */ protected static void makeAccessible(final Field field) { if (!ModifierisPublic(fieldgetModifiers()) || !ModifierisPublic(fieldgetDeclaringClass()getModifiers())) { fieldsetAccessible(true) } }

   /** * 通過反射獲得定義Class時聲明的父類的泛型參數的類型 如public UserDao extends HibernateDao<User> * * @param clazz *            The class to introspect * @return the first generic declaration or Objectclass if cannot be *         determined */ @SuppressWarnings(unchecked

   public static Class getSuperClassGenricType(final Class clazz) { return getSuperClassGenricType(clazz }

   /** * 通過反射獲得定義Class時聲明的父類的泛型參數的類型 如public UserDao extends * HibernateDao<UserLong> * * @param clazz *            clazz The class to introspect * @param index *            the Index of the generic ddeclarationstart from * @return the index generic declaration or Objectclass if cannot be *         determined */

   @SuppressWarnings(unchecked

   public static Class getSuperClassGenricType(final Class clazz final int index) {

   Type genType = clazzgetGenericSuperclass()

   if (!(genType instanceof ParameterizedType)) { loggerwarn(clazzgetSimpleName() + s superclass not ParameterizedType return Objectclass }

   Type[] params = ((ParameterizedType) genType)getActualTypeArguments()

   if (index >= paramslength || index < ) { loggerwarn(Index + index + Size of + clazzgetSimpleName() + s Parameterized Type + paramslength) return Objectclass } if (!(params[index] instanceof Class)) { loggerwarn(clazzgetSimpleName() + not set the actual class on superclass generic parameter return Objectclass } return (Class) params[index] }

   /** * 提取集合中的對象的屬性組合成List * * @param collection *            來源集合

   * @param propertityName *            要提取的屬性名

   */ @SuppressWarnings(unchecked

   public static List fetchElementPropertyToList(final Collection collection final String propertyName) throws Exception {

   List list = new ArrayList()

   for (Object obj collection) { listadd(PropertyUtilsgetProperty(obj propertyName)) }

   return list }

   /** * 提取集合中的對象的屬性組合成由分割符分隔的字符串

   * * @param collection *            來源集合

   * @param propertityName *            要提取的屬性名

   * @param separator *            分隔符

   */ @SuppressWarnings(unchecked

   public static String fetchElementPropertyToString(final Collection collection final String propertyName final String separator) throws Exception { List list = fetchElementPropertyToList(collection propertyName) return StringUtilsjoin(listtoArray() separator) } }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26718.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.