001 | import java.lang.reflect.Field; |
002 | import java.lang.reflect.InvocationTargetException; |
003 | import java.lang.reflect.Method; |
004 | import java.lang.reflect.Modifier; |
005 | import java.lang.reflect.ParameterizedType; |
006 | import java.lang.reflect.Type; |
007 | import java.util.ArrayList; |
008 | import java.util.Collection; |
009 | import java.util.Date; |
010 | import java.util.List; |
012 | import org.apache.commons.beanutils.ConvertUtils; |
013 | import org.apache.commons.beanutils.PropertyUtils; |
014 | import org.apache.commons.beanutils.converters.DateConverter; |
015 | import org.apache.commons.lang.StringUtils; |
016 | import org.slf4j.Logger; |
017 | import org.slf4j.LoggerFactory; |
018 | import org.springframework.util.Assert; |
023 | * 提供访问私有变量,获取泛型类型Class, 提取集合中元素的属性, 转换字符串到对象等Util函数. |
026 | public class ReflectionUtils { |
028 | private static Logger logger = LoggerFactory.getLogger(ReflectionUtils. class ); |
031 | DateConverter dc = new DateConverter(); |
032 | dc.setUseLocaleFormat( true ); |
033 | dc.setPatterns( new String[] { "yyyy-MM-dd" , "yyyy-MM-dd HH:mm:ss" }); |
034 | ConvertUtils.register(dc, Date. class ); |
040 | public static Object invokeGetterMethod(Object target, String propertyName) { |
041 | String getterMethodName = "get" + StringUtils.capitalize(propertyName); |
042 | return invokeMethod(target, getterMethodName, new Class[] {}, new Object[] {}); |
046 | * 调用Setter方法.使用value的Class来查找Setter方法. |
048 | public static void invokeSetterMethod(Object target, String propertyName, Object value) { |
049 | invokeSetterMethod(target, propertyName, value, null ); |
055 | * @param propertyType 用于查找Setter方法,为空时使用value的Class替代. |
057 | public static void invokeSetterMethod(Object target, String propertyName, Object value, Class<?> propertyType) { |
058 | Class<?> type = propertyType != null ? propertyType : value.getClass(); |
059 | String setterMethodName = "set" + StringUtils.capitalize(propertyName); |
060 | invokeMethod(target, setterMethodName, new Class[] { type }, new Object[] { value }); |
064 | * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. |
066 | public static Object getFieldValue( final Object object, final String fieldName) { |
067 | Field field = getDeclaredField(object, fieldName); |
070 | throw new IllegalArgumentException( "Could not find field [" + fieldName + "] on target [" + object + "]" ); |
073 | makeAccessible(field); |
075 | Object result = null ; |
077 | result = field.get(object); |
078 | } catch (IllegalAccessException e) { |
079 | logger.error( "不可能抛出的异常{}" , e.getMessage()); |
085 | * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. |
087 | public static void setFieldValue( final Object object, final String fieldName, final Object value) { |
088 | Field field = getDeclaredField(object, fieldName); |
091 | throw new IllegalArgumentException( "Could not find field [" + fieldName + "] on target [" + object + "]" ); |
094 | makeAccessible(field); |
097 | field.set(object, value); |
098 | } catch (IllegalAccessException e) { |
099 | logger.error( "不可能抛出的异常:{}" , e.getMessage()); |
104 | * 直接调用对象方法, 无视private/protected修饰符. |
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 + "]" ); |
113 | method.setAccessible( true ); |
116 | return method.invoke(object, parameters); |
117 | } catch (Exception e) { |
118 | throw convertReflectionExceptionToUnchecked(e); |
123 | * 循环向上转型, 获取对象的DeclaredField. |
125 | * 如向上转型到Object仍无法找到, 返回null. |
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 |
133 | return superClass.getDeclaredField(fieldName); |
134 | } catch (NoSuchFieldException e) { |
144 | protected static void makeAccessible( final Field field) { |
145 | if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) { |
146 | field.setAccessible( true ); |
151 | * 循环向上转型, 获取对象的DeclaredMethod. |
153 | * 如向上转型到Object仍无法找到, 返回null. |
155 | protected static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) { |
156 | Assert.notNull(object, "object不能为空" ); |
158 | for (Class<?> superClass = object.getClass(); superClass != Object. class ; superClass = superClass |
161 | return superClass.getDeclaredMethod(methodName, parameterTypes); |
162 | } catch (NoSuchMethodException e) { |
170 | * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. |
171 | * 如无法找到, 返回Object.class. |
173 | * public UserDao extends HibernateDao<User> |
175 | * @param clazz The class to introspect |
176 | * @return the first generic declaration, or Object.class if cannot be determined |
178 | @SuppressWarnings ( "unchecked" ) |
179 | public static <T> Class<T> getSuperClassGenricType( final Class clazz) { |
180 | return getSuperClassGenricType(clazz, 0 ); |
184 | * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. |
185 | * 如无法找到, 返回Object.class. |
187 | * 如public UserDao extends HibernateDao<User,Long> |
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 |
193 | @SuppressWarnings ( "unchecked" ) |
194 | public static Class getSuperClassGenricType( final Class clazz, final int index) { |
195 | Type genType = clazz.getGenericSuperclass(); |
197 | if (!(genType instanceof ParameterizedType)) { |
198 | logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType" ); |
202 | Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); |
204 | if (index >= params.length || index < 0 ) { |
205 | logger.warn( "Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " |
209 | if (!(params[index] instanceof Class)) { |
210 | logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter" ); |
214 | return (Class) params[index]; |
218 | * 提取集合中的对象的属性(通过getter函数), 组合成List. |
220 | * @param collection 来源集合. |
221 | * @param propertyName 要提取的属性名. |
223 | @SuppressWarnings ( "unchecked" ) |
224 | public static List convertElementPropertyToList( final Collection collection, final String propertyName) { |
225 | List list = new ArrayList(); |
228 | for (Object obj : collection) { |
229 | list.add(PropertyUtils.getProperty(obj, propertyName)); |
231 | } catch (Exception e) { |
232 | throw convertReflectionExceptionToUnchecked(e); |
239 | * 提取集合中的对象的属性(通过getter函数), 组合成由分割符分隔的字符串. |
241 | * @param collection 来源集合. |
242 | * @param propertyName 要提取的属性名. |
243 | * @param separator 分隔符. |
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); |
255 | * @param value 待转换的字符串 |
256 | * @param toType 转换目标类型 |
258 | @SuppressWarnings ( "unchecked" ) |
259 | public static <T> T convertStringToObject(String value, Class<T> toType) { |
261 | return (T) ConvertUtils.convert(value, toType); |
262 | } catch (Exception e) { |
263 | throw convertReflectionExceptionToUnchecked(e); |
268 | * 将反射时的checked exception转换为unchecked exception. |
270 | public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) { |
271 | return convertReflectionExceptionToUnchecked( null , e); |
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; |
284 | return new RuntimeException(desc, e); |
287 | public static final <T> T getNewInstance(Class<T> cls) { |
289 | return cls.newInstance(); |
290 | } catch (InstantiationException e) { |
292 | } catch (IllegalAccessException e) { |
|