Java tutorial
/** * Copyright (c) 2012-2014 http://www.eryansky.com * * Licensed under the Apache License, Version 2.0 (the "License"); */ package org.nerve.utils.reflection; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.nerve.utils.Assert; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.ArrayList; import java.util.List; /** * ??. * * ??getter/setter, ???, ?, ?Class, AOP. * */ public class ReflectionUtils { private static final String SETTER_PREFIX = "set"; private static final String GETTER_PREFIX = "get"; private static final String CGLIB_CLASS_SEPARATOR = "$$"; /** * Getter. * * @param target Object * @param propertyName ?? * @param <T> * @return Object */ public static <T> T invokeGetter(Object target, String propertyName) { String getterMethodName = "get" + StringUtils.capitalize(propertyName); return (T) invokeMethod(target, getterMethodName, new Class[] {}, new Object[] {}); } /** * Setter, ??? * @param obj * @param propertyName ?? * @param value */ public static void invokeSetter(Object obj, String propertyName, Object value) { String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(propertyName); invokeMethodByName(obj, setterMethodName, new Object[] { value }); } /** * Getter.???.??. * @param obj * @param propertyName ?? * @return */ public static Object invokeGetter2(Object obj, String propertyName) { Object object = obj; for (String name : StringUtils.split(propertyName, ".")) { String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name); object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); } return object; } /** * Setter, ??????.??. * @param obj * @param propertyName ?? * @param value */ public static void invokeSetter2(Object obj, String propertyName, Object value) { Object object = obj; String[] names = StringUtils.split(propertyName, "."); for (int i = 0; i < names.length; i++) { if (i < names.length - 1) { String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]); object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); } else { String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]); invokeMethodByName(object, setterMethodName, new Object[] { value }); } } } /** * ?, private/protected, ??getter. * * @param target * Object * @param fieldName * ?? * @param <T> * @return Object */ public static <T> T getFieldValue(final Object target, final String fieldName) { Assert.notNull(target, "target?"); Assert.notNull(fieldName, "fieldName?"); Field field = getAccessibleField(target, fieldName); if (field == null) { throw new IllegalArgumentException( "? [" + fieldName + "] [" + target + "] "); } Object result = null; try { result = field.get(target); } catch (IllegalAccessException e) { } return (T) result; } /** * , private/protected, ??setter. * @param obj * @param fieldName ?? * @param value */ public static void setFieldValue(final Object obj, final String fieldName, final Object value) { Field field = getAccessibleField(obj, fieldName); if (field == null) { throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]"); } try { field.set(obj, value); } catch (IllegalAccessException e) { e.printStackTrace(); } } /** * , private/protected. * ?getAccessibleMethod()Method????. * ????+? * @param obj * @param methodName ?? * @param parameterTypes ? * @param args ? * @return object */ public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes, final Object[] args) { Method method = getAccessibleMethod(obj, methodName, parameterTypes); if (method == null) { throw new IllegalArgumentException( "Could not find method [" + methodName + "] on target [" + obj + "]"); } try { return method.invoke(obj, args); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } } /** * , private/protected * ?getAccessibleMethodByName()Method????. * ??????? * @param obj * @param methodName ?? * @param args ? * @return object */ public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) { Method method = getAccessibleMethodByName(obj, methodName); if (method == null) { throw new IllegalArgumentException( "Could not find method [" + methodName + "] on target [" + obj + "]"); } try { return method.invoke(obj, args); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } } /** * ?, ?DeclaredField, ?. * * ?Object?, null. * @param obj * @param fieldName ?? * @return Field */ public static Field getAccessibleField(final Object obj, final String fieldName) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(fieldName, "fieldName can't be blank"); for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass .getSuperclass()) { try { Field field = superClass.getDeclaredField(fieldName); makeAccessible(field); return field; } catch (NoSuchFieldException e) {//NOSONAR // Field??,? } } return null; } /** * ?, ?DeclaredMethod,?. * ?Object?, null. * ???+? * * ?. ?Method,?Method.invoke(Object obj, Object... args) * @param obj * @param methodName ?? * @param parameterTypes ? * @return Method */ public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType .getSuperclass()) { try { Method method = searchType.getDeclaredMethod(methodName, parameterTypes); makeAccessible(method); return method; } catch (NoSuchMethodException e) { // Method??,? } } return null; } /** * ?, ?DeclaredMethod,?. * ?Object?, null. * ???? * * ?. ?Method,?Method.invoke(Object obj, Object... args) * @param obj * @param methodName ?? * @return Method */ public static Method getAccessibleMethodByName(final Object obj, final String methodName) { Validate.notNull(obj, "object can't be null"); Validate.notBlank(methodName, "methodName can't be blank"); for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType .getSuperclass()) { Method[] methods = searchType.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { makeAccessible(method); return method; } } } return null; } /** * ?private/protectedpublic?????JDKSecurityManager * @param method */ public static void makeAccessible(Method method) { if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) { method.setAccessible(true); } } /** * ?private/protected???public?????JDKSecurityManager * @param field */ public static void makeAccessible(Field field) { if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) { field.setAccessible(true); } } /** * ??, Class?, ? * , Object.class. * eg. * public UserDao extends HibernateDao?User * * @param clazz The class to introspect * @param <T> * @return the first generic declaration, or Object.class if cannot be determined */ public static <T> Class<T> getClassGenricType(final Class clazz) { return getClassGenricType(clazz, 0); } /** * ??, Class?. * , Object.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 */ public static Class getClassGenricType(final Class clazz, final int index) { Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType)) { System.err.println(clazz.getSimpleName() + "'s superclass not ParameterizedType"); return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { System.err.println("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length); return Object.class; } if (!(params[index] instanceof Class)) { System.err.println(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); return Object.class; } return (Class) params[index]; } public static Class<?> getTargetClass(Object target) { Assert.notNull(target, "target?"); return getTargetClass(target.getClass()); } /** * ?Classcglib AOPCGLIBClass?Class * * @param targetClass * * @return Class */ public static Class<?> getTargetClass(Class<?> targetClass) { Assert.notNull(targetClass, "targetClass?"); Class clazz = targetClass; if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) { Class<?> superClass = clazz.getSuperclass(); if (superClass != null && !Object.class.equals(superClass)) { return superClass; } } return clazz; } /** * ??checked exception?unchecked exception. * @param e * @return RuntimeException */ public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) { if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException || e instanceof NoSuchMethodException) { return new IllegalArgumentException(e); } else if (e instanceof InvocationTargetException) { return new RuntimeException(((InvocationTargetException) e).getTargetException()); } else if (e instanceof RuntimeException) { return (RuntimeException) e; } return new RuntimeException("Unexpected Checked Exception.", e); } public static <T> T getAnnotation(Object target, Class annotationClass) { Assert.notNull(target, "target?"); return (T) getAnnotation(target.getClass(), annotationClass); } public static <T extends Annotation> T getAnnotation(Class targetClass, Class annotationClass) { Assert.notNull(targetClass, "targetClass?"); Assert.notNull(annotationClass, "annotationClass?"); if (targetClass.isAnnotationPresent(annotationClass)) { return (T) targetClass.getAnnotation(annotationClass); } return null; } /** * ?ObjectannotationClass * * @param target * Object * @param annotationClass * Annotation * @param <T> * @return {@link Annotation} */ public static <T extends Annotation> List<T> getAnnotations(Object target, Class annotationClass) { Assert.notNull(target, "target?"); return getAnnotations(getTargetClass(target), annotationClass); } /** * ?annotationClass * @param targetClass Class * @param annotationClass Class * @param <T> * @return */ public static <T extends Annotation> List<T> getAnnotations(Class targetClass, Class annotationClass) { Assert.notNull(targetClass, "targetClass?"); Assert.notNull(annotationClass, "annotationClass?"); List<T> result = new ArrayList<T>(); Annotation annotation = targetClass.getAnnotation(annotationClass); if (annotation != null) { result.add((T) annotation); } Constructor[] constructors = targetClass.getDeclaredConstructors(); // ? CollectionUtils.addAll(result, getAnnotations(constructors, annotationClass).iterator()); Field[] fields = targetClass.getDeclaredFields(); // ? CollectionUtils.addAll(result, getAnnotations(fields, annotationClass).iterator()); Method[] methods = targetClass.getDeclaredMethods(); // ? CollectionUtils.addAll(result, getAnnotations(methods, annotationClass).iterator()); for (Class<?> superClass = targetClass.getSuperclass(); superClass == null || superClass == Object.class; superClass = superClass.getSuperclass()) { List<T> temp = (List<T>) getAnnotations(superClass, annotationClass); if (CollectionUtils.isNotEmpty(temp)) { CollectionUtils.addAll(result, temp.iterator()); } } return result; } /** * ?fieldannotationClass * * @param field * field * @param annotationClass * annotationClass * @param <T> * @return {@link Annotation} */ public static <T extends Annotation> T getAnnotation(Field field, Class annotationClass) { Assert.notNull(field, "field?"); Assert.notNull(annotationClass, "annotationClass?"); field.setAccessible(true); if (field.isAnnotationPresent(annotationClass)) { return (T) field.getAnnotation(annotationClass); } return null; } /** * ?field?annotationClass * * @param fields * field * @param annotationClass * annotationClass * @param <T> * @return List */ public static <T extends Annotation> List<T> getAnnotations(Field[] fields, Class annotationClass) { if (ArrayUtils.isEmpty(fields)) { return null; } List<T> result = new ArrayList<T>(); for (Field field : fields) { field.setAccessible(true); Annotation annotation = getAnnotation(field, annotationClass); if (annotation != null) { result.add((T) annotation); } } return result; } /** * ?methodannotationClass * * @param method * method * @param annotationClass * annotationClass * @param <T> * @return {@link Annotation} */ public static <T extends Annotation> T getAnnotation(Method method, Class annotationClass) { Assert.notNull(method, "method?"); Assert.notNull(annotationClass, "annotationClass?"); method.setAccessible(true); if (method.isAnnotationPresent(annotationClass)) { return (T) method.getAnnotation(annotationClass); } return null; } /** * ?method?annotationClass * * @param methods * method * @param annotationClass * annotationClass * @param <T> * @return List */ public static <T extends Annotation> List<T> getAnnotations(Method[] methods, Class annotationClass) { if (ArrayUtils.isEmpty(methods)) { return null; } List<T> result = new ArrayList<T>(); for (Method method : methods) { Annotation annotation = getAnnotation(method, annotationClass); if (annotation != null) { result.add((T) annotation); } } return result; } /** * ?constructorannotationClass * * @param constructor * constructor * @param annotationClass * annotationClass * @param <T> * @return {@link Annotation} */ public static <T extends Annotation> T getAnnotation(Constructor constructor, Class annotationClass) { Assert.notNull(constructor, "constructor?"); Assert.notNull(annotationClass, "annotationClass?"); constructor.setAccessible(true); if (constructor.isAnnotationPresent(annotationClass)) { return (T) constructor.getAnnotation(annotationClass); } return null; } /** * ?constructors?annotationClass * * @param constructors * constructor * @param annotationClass * annotationClass * @param <T> * @return List */ public static <T extends Annotation> List<T> getAnnotations(Constructor<T>[] constructors, Class annotationClass) { if (ArrayUtils.isEmpty(constructors)) { return null; } List<T> result = new ArrayList<T>(); for (Constructor constructor : constructors) { Annotation annotation = getAnnotation(constructor, annotationClass); if (annotation != null) { result.add((T) annotation); } } return result; } }