Java tutorial
/** * Copyright (c) 2012-2014 http://www.eryansky.com * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.zc.util.refelect; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.*; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ??. * * ??getter/setter, ???, ?, ?Class, AOP. * @mailto zhoucheng2007@gmail.com * @date 2013-3-24 ?4:17:27 * */ @SuppressWarnings(value = "unchecked") public class Reflector { private static final String SETTER_PREFIX = "set"; private static final String GETTER_PREFIX = "get"; private static final String CGLIB_CLASS_SEPARATOR = "$$"; private static Logger logger = LoggerFactory.getLogger(Reflector.class); /** * Getter. * * @param target * Object * @param propertyName * ?? * * @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, ??? */ public static void invokeSetter(Object obj, String propertyName, Object value) { String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(propertyName); invokeMethodByName(obj, setterMethodName, new Object[] { value }); } /** * Getter. * ???.??. */ 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, ??? * ???.??. */ 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 * ?? * * @return Object */ public static <T> T getFieldValue(final Object target, final String 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) { logger.error("??{}", e.getMessage()); } return (T) result; } /** * , private/protected, ??setter. */ 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) { logger.error("??:{}", e.getMessage()); } } /** * , private/protected. * ?getAccessibleMethod()Method????. * ????+? */ 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????. * ??????? */ 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. */ public static Field getAccessibleField(final Object obj, final String fieldName) { 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) */ public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) { 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) */ public static Method getAccessibleMethodByName(final Object obj, final String methodName) { 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 */ 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 */ 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 * @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)) { logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType"); return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length); return Object.class; } if (!(params[index] instanceof Class)) { logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); return Object.class; } return (Class) params[index]; } public static Class<?> getTargetClass(Object target) { return getTargetClass(target.getClass()); } /** * ?Classcglib AOPCGLIBClass?Class * * @param targetClass * * @return Class */ public static Class<?> getTargetClass(Class<?> 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. */ 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); } /** * ? * * @param target * Object * @param annotationClass * * * @return Object */ public static <T> T getAnnotation(Object target, Class annotationClass) { return (T) getAnnotation(target.getClass(), annotationClass); } /** * ? * * @param targetClass * Class * @param annotationClass * Class * * @return Object */ public static <T extends Annotation> T getAnnotation(Class targetClass, Class annotationClass) { if (targetClass.isAnnotationPresent(annotationClass)) { return (T) targetClass.getAnnotation(annotationClass); } return null; } /** * ?ObjectannotationClass * * @param target * Object * @param annotationClass * Annotation * * @return {@link java.lang.annotation.Annotation} */ public static <T extends Annotation> List<T> getAnnotations(Object target, Class annotationClass) { return getAnnotations(getTargetClass(target), annotationClass); } /** * * ?annotationClass * * @param targetClass * Class * @param annotationClass * Class * * @return List */ public static <T extends Annotation> List<T> getAnnotations(Class targetClass, Class 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 * * @return {@link java.lang.annotation.Annotation} */ public static <T extends Annotation> T getAnnotation(Field field, Class annotationClass) { field.setAccessible(true); if (field.isAnnotationPresent(annotationClass)) { return (T) field.getAnnotation(annotationClass); } return null; } /** * ?field?annotationClass * * @param fields * field * @param annotationClass * annotationClass * * @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 * * @return {@link java.lang.annotation.Annotation} */ public static <T extends Annotation> T getAnnotation(Method method, Class annotationClass) { method.setAccessible(true); if (method.isAnnotationPresent(annotationClass)) { return (T) method.getAnnotation(annotationClass); } return null; } /** * ?method?annotationClass * * @param methods * method * @param annotationClass * annotationClass * * @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 * * @return {@link java.lang.annotation.Annotation} */ public static <T extends Annotation> T getAnnotation(Constructor constructor, Class annotationClass) { constructor.setAccessible(true); if (constructor.isAnnotationPresent(annotationClass)) { return (T) constructor.getAnnotation(annotationClass); } return null; } /** * ?constructors?annotationClass * * @param constructors * constructor * @param annotationClass * annotationClass * * @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; } }