spring中的反射工具类ReflectionUtils

spring提供的ReflectionUtils可以简化项目中反射代码的复杂性
在项目中如果使用最原始的方法来开发反射的功能的话肯能会比较复杂,需要处理一大堆异常以及访问权限等问题。spring中提供了ReflectionUtils这个反射的工具类

获取方法
根据bean的名称、需要调用的方法名、和要传递的参数来调用该bean的特定方法。
ReflectionUtils.findMethod()方法:

public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes)

依次需要传入 class对象、方法名、参数类型

Method method = ReflectUtil.getMethod(obj.getClass(), methodName);

obj 是bean对象,getMethod方法有多个重载,可以声明参数

执行方法
第一种方式
使用java原始的方式

method.invoke(obj, args);

method 是反射获取的方法实体,obj为bean 对象,args 是参数。

第二种方式,也是推荐使用方式
使用ReflectUtil对象

ReflectionUtils.invokeMethod(method, obj, args);

method 方法实体,obj bean实体,args参数

/*******************************************************************

  • Company: Fuzhou Rockchip Electronics Co., Ltd
  • Filename: ReflectionUtils.java
  • Description:
  • @author: fxw@rock-chips.com
  • Modification History:
  • Date Author Version Description

  • 2012-3-11 xwf 1.0 create
    *******************************************************************/

package com.rk_itvui.settings;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.UndeclaredThrowableException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public abstract class ReflectionUtils {
/**
* Invoke the specified {@link Method} against the supplied target object with no arguments.
* The target object can be null when invoking a static {@link Method}.
*

Thrown exceptions are handled via a call to {@link #handleReflectionException}.
* @param method the method to invoke
* @param target the target object to invoke the method on
* @return the invocation result, if any
* @see #invokeMethod(java.lang.reflect.Method, Object, Object[])
*/
public static Object invokeMethod(Method method, Object target) {
return invokeMethod(method, target, new Object[0]);
}

/**
 * Invoke the specified {@link Method} against the supplied target object with the
 * supplied arguments. The target object can be <code>null</code> when invoking a
 * static {@link Method}.
 * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}.
 * @param method the method to invoke
 * @param target the target object to invoke the method on
 * @param args the invocation arguments (may be <code>null</code>)
 * @return the invocation result, if any
 */
public static Object invokeMethod(Method method, Object target, Object... args) {
	try {
		return method.invoke(target, args);
	}
	catch (Exception ex) {
		handleReflectionException(ex);
	}
	throw new IllegalStateException("Should never get here");
}

/**
 * Invoke the specified JDBC API {@link Method} against the supplied target
 * object with no arguments.
 * @param method the method to invoke
 * @param target the target object to invoke the method on
 * @return the invocation result, if any
 * @throws SQLException the JDBC API SQLException to rethrow (if any)
 * @see #invokeJdbcMethod(java.lang.reflect.Method, Object, Object[])
 */
public static Object invokeJdbcMethod(Method method, Object target) throws SQLException {
	return invokeJdbcMethod(method, target, new Object[0]);
}

/**
 * Invoke the specified JDBC API {@link Method} against the supplied target
 * object with the supplied arguments.
 * @param method the method to invoke
 * @param target the target object to invoke the method on
 * @param args the invocation arguments (may be <code>null</code>)
 * @return the invocation result, if any
 * @throws SQLException the JDBC API SQLException to rethrow (if any)
 * @see #invokeMethod(java.lang.reflect.Method, Object, Object[])
 */
public static Object invokeJdbcMethod(Method method, Object target, Object... args) throws SQLException {
	try {
		return method.invoke(target, args);
	}
	catch (IllegalAccessException ex) {
		handleReflectionException(ex);
	}
	catch (InvocationTargetException ex) {
		if (ex.getTargetException() instanceof SQLException) {
			throw (SQLException) ex.getTargetException();
		}
		handleInvocationTargetException(ex);
	}
	throw new IllegalStateException("Should never get here");
}

/**
 * Handle the given reflection exception. Should only be called if no
 * checked exception is expected to be thrown by the target method.
 * <p>Throws the underlying RuntimeException or Error in case of an
 * InvocationTargetException with such a root cause. Throws an
 * IllegalStateException with an appropriate message else.
 * @param ex the reflection exception to handle
 */
public static void handleReflectionException(Exception ex) {
	if (ex instanceof NoSuchMethodException) {
		throw new IllegalStateException("Method not found: " + ex.getMessage());
	}
	if (ex instanceof IllegalAccessException) {
		throw new IllegalStateException("Could not access method: " + ex.getMessage());
	}
	if (ex instanceof InvocationTargetException) {
		handleInvocationTargetException((InvocationTargetException) ex);
	}
	if (ex instanceof RuntimeException) {
		throw (RuntimeException) ex;
	}
	throw new UndeclaredThrowableException(ex);
}

/**
 * Handle the given invocation target exception. Should only be called if no
 * checked exception is expected to be thrown by the target method.
 * <p>Throws the underlying RuntimeException or Error in case of such a root
 * cause. Throws an IllegalStateException else.
 * @param ex the invocation target exception to handle
 */
public static void handleInvocationTargetException(InvocationTargetException ex) {
	rethrowRuntimeException(ex.getTargetException());
}

/**
 * Rethrow the given {@link Throwable exception}, which is presumably the
 * <em>target exception</em> of an {@link InvocationTargetException}. Should
 * only be called if no checked exception is expected to be thrown by the
 * target method.
 * <p>Rethrows the underlying exception cast to an {@link RuntimeException} or
 * {@link Error} if appropriate; otherwise, throws an
 * {@link IllegalStateException}.
 * @param ex the exception to rethrow
 * @throws RuntimeException the rethrown exception
 */
public static void rethrowRuntimeException(Throwable ex) {
	if (ex instanceof RuntimeException) {
		throw (RuntimeException) ex;
	}
	if (ex instanceof Error) {
		throw (Error) ex;
	}
	throw new UndeclaredThrowableException(ex);
}

/**
 * Rethrow the given {@link Throwable exception}, which is presumably the
 * <em>target exception</em> of an {@link InvocationTargetException}. Should
 * only be called if no checked exception is expected to be thrown by the
 * target method.
 * <p>Rethrows the underlying exception cast to an {@link Exception} or
 * {@link Error} if appropriate; otherwise, throws an
 * {@link IllegalStateException}.
 * @param ex the exception to rethrow
 * @throws Exception the rethrown exception (in case of a checked exception)
 */
public static void rethrowException(Throwable ex) throws Exception {
	if (ex instanceof Exception) {
		throw (Exception) ex;
	}
	if (ex instanceof Error) {
		throw (Error) ex;
	}
	throw new UndeclaredThrowableException(ex);
}

/**
 * Determine whether the given method explicitly declares the given
 * exception or one of its superclasses, which means that an exception of
 * that type can be propagated as-is within a reflective invocation.
 * @param method the declaring method
 * @param exceptionType the exception to throw
 * @return <code>true</code> if the exception can be thrown as-is;
 * <code>false</code> if it needs to be wrapped
 */
public static boolean declaresException(Method method, Class<?> exceptionType) {
	Class<?>[] declaredExceptions = method.getExceptionTypes();
	for (Class<?> declaredException : declaredExceptions) {
		if (declaredException.isAssignableFrom(exceptionType)) {
			return true;
		}
	}
	return false;
}

/**
 * Determine whether the given field is a "public static final" constant.
 * @param field the field to check
 */
public static boolean isPublicStaticFinal(Field field) {
	int modifiers = field.getModifiers();
	return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
}

/**
 * Determine whether the given method is an "equals" method.
 * @see java.lang.Object#equals(Object)
 */
public static boolean isEqualsMethod(Method method) {
	if (method == null || !method.getName().equals("equals")) {
		return false;
	}
	Class<?>[] paramTypes = method.getParameterTypes();
	return (paramTypes.length == 1 && paramTypes[0] == Object.class);
}

/**
 * Determine whether the given method is a "hashCode" method.
 * @see java.lang.Object#hashCode()
 */
public static boolean isHashCodeMethod(Method method) {
	return (method != null && method.getName().equals("hashCode") && method.getParameterTypes().length == 0);
}

/**
 * Determine whether the given method is a "toString" method.
 * @see java.lang.Object#toString()
 */
public static boolean isToStringMethod(Method method) {
	return (method != null && method.getName().equals("toString") && method.getParameterTypes().length == 0);
}

/**
 * Determine whether the given method is originally declared by {@link java.lang.Object}.
 */
public static boolean isObjectMethod(Method method) {
	try {
		Object.class.getDeclaredMethod(method.getName(), method.getParameterTypes());
		return true;
	} catch (SecurityException ex) {
		return false;
	} catch (NoSuchMethodException ex) {
		return false;
	}
}

/**
 * Make the given field accessible, explicitly setting it accessible if
 * necessary. The <code>setAccessible(true)</code> method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 * @param field the field to make accessible
 * @see java.lang.reflect.Field#setAccessible
 */
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);
	}
}

/**
 * Make the given method accessible, explicitly setting it accessible if
 * necessary. The <code>setAccessible(true)</code> method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 * @param method the method to make accessible
 * @see java.lang.reflect.Method#setAccessible
 */
public static void makeAccessible(Method method) {
	if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
			&& !method.isAccessible()) {
		method.setAccessible(true);
	}
}

/**
 * Make the given constructor accessible, explicitly setting it accessible
 * if necessary. The <code>setAccessible(true)</code> method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 * @param ctor the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
public static void makeAccessible(Constructor<?> ctor) {
	if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers()))
			&& !ctor.isAccessible()) {
		ctor.setAccessible(true);
	}
}

/**
 * Perform the given callback operation on all matching methods of the given
 * class and superclasses.
 * <p>The same named method occurring on subclass and superclass will appear
 * twice, unless excluded by a {@link MethodFilter}.
 * @param clazz class to start looking at
 * @param mc the callback to invoke for each method
 * @see #doWithMethods(Class, MethodCallback, MethodFilter)
 */
public static void doWithMethods(Class<?> clazz, MethodCallback mc) throws IllegalArgumentException {
	doWithMethods(clazz, mc, null);
}

/**
 * Perform the given callback operation on all matching methods of the given
 * class and superclasses (or given interface and super-interfaces).
 * <p>The same named method occurring on subclass and superclass will appear
 * twice, unless excluded by the specified {@link MethodFilter}.
 * @param clazz class to start looking at
 * @param mc the callback to invoke for each method
 * @param mf the filter that determines the methods to apply the callback to
 */
public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf)
		throws IllegalArgumentException {

	// Keep backing up the inheritance hierarchy.
	Method[] methods = clazz.getDeclaredMethods();
	for (Method method : methods) {
		if (mf != null && !mf.matches(method)) {
			continue;
		}
		try {
			mc.doWith(method);
		}
		catch (IllegalAccessException ex) {
			throw new IllegalStateException("Shouldn't be illegal to access method '" + method.getName()
					+ "': " + ex);
		}
	}
	if (clazz.getSuperclass() != null) {
		doWithMethods(clazz.getSuperclass(), mc, mf);
	}
	else if (clazz.isInterface()) {
		for (Class<?> superIfc : clazz.getInterfaces()) {
			doWithMethods(superIfc, mc, mf);
		}
	}
}

/**
 * Get all declared methods on the leaf class and all superclasses. Leaf
 * class methods are included first.
 */
public static Method[] getAllDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {
	final List<Method> methods = new ArrayList<Method>(32);
	doWithMethods(leafClass, new MethodCallback() {
		public void doWith(Method method) {
			methods.add(method);
		}
	});
	return methods.toArray(new Method[methods.size()]);
}

/**
 * Get the unique set of declared methods on the leaf class and all superclasses. Leaf
 * class methods are included first and while traversing the superclass hierarchy any methods found
 * with signatures matching a method already included are filtered out.
 */
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {
	final List<Method> methods = new ArrayList<Method>(32);
	doWithMethods(leafClass, new MethodCallback() {
		public void doWith(Method method) {
			Method methodBeingOverriddenWithCovariantReturnType = null;

			for (Method existingMethod : methods) {
				if (method.getName().equals(existingMethod.getName()) &&
						Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {
					// is this a covariant return type situation?
					if (existingMethod.getReturnType() != method.getReturnType() &&
							existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {
						methodBeingOverriddenWithCovariantReturnType = existingMethod;
					}
					break;
				}
			}
			if (methodBeingOverriddenWithCovariantReturnType != null) {
				methods.remove(methodBeingOverriddenWithCovariantReturnType);
			}
		}
	});
	return methods.toArray(new Method[methods.size()]);
}

/**
 * Invoke the given callback on all fields in the target class, going up the
 * class hierarchy to get all declared fields.
 * @param clazz the target class to analyze
 * @param fc the callback to invoke for each field
 */
public static void doWithFields(Class<?> clazz, FieldCallback fc) throws IllegalArgumentException {
	doWithFields(clazz, fc, null);
}

/**
 * Invoke the given callback on all fields in the target class, going up the
 * class hierarchy to get all declared fields.
 * @param clazz the target class to analyze
 * @param fc the callback to invoke for each field
 * @param ff the filter that determines the fields to apply the callback to
 */
public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff)
		throws IllegalArgumentException {

	// Keep backing up the inheritance hierarchy.
	Class<?> targetClass = clazz;
	do {
		Field[] fields = targetClass.getDeclaredFields();
		for (Field field : fields) {
			// Skip static and final fields.
			if (ff != null && !ff.matches(field)) {
				continue;
			}
			try {
				fc.doWith(field);
			}
			catch (IllegalAccessException ex) {
				throw new IllegalStateException(
						"Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
			}
		}
		targetClass = targetClass.getSuperclass();
	}
	while (targetClass != null && targetClass != Object.class);
}

/**
 * Given the source object and the destination, which must be the same class
 * or a subclass, copy all fields, including inherited fields. Designed to
 * work on objects with public no-arg constructors.
 * @throws IllegalArgumentException if the arguments are incompatible
 */
public static void shallowCopyFieldState(final Object src, final Object dest) throws IllegalArgumentException {
	if (src == null) {
		throw new IllegalArgumentException("Source for field copy cannot be null");
	}
	if (dest == null) {
		throw new IllegalArgumentException("Destination for field copy cannot be null");
	}
	if (!src.getClass().isAssignableFrom(dest.getClass())) {
		throw new IllegalArgumentException("Destination class [" + dest.getClass().getName()
				+ "] must be same or subclass as source class [" + src.getClass().getName() + "]");
	}
	doWithFields(src.getClass(), new FieldCallback() {
		public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
			makeAccessible(field);
			Object srcValue = field.get(src);
			field.set(dest, srcValue);
		}
	}, COPYABLE_FIELDS);
}


/**
 * Get specify field value with the given the name of field
 * @param obj the target object
 * @param fieldname the name of field
 * @return the field value if exist
 */
public Object getFieldValue(Object obj, String fieldName) {
    Object result = null;
    Class<?> objClass = obj.getClass();
    Field field;
	try {
		field = objClass.getField(fieldName);
        result = field.get(obj);
	} catch (Exception ex) {
		handleReflectionException(ex);
	}
    return result;
}

/**
 * Get specify static field value with the given the name of field
 * @param className the class to introspect
 * @param fieldName the name of field
 * @return the field value if exist
 */
public static Object getStaticFieldValue(String className, String fieldName) {
	try {
        Class<?> cls = Class.forName(className);
        Field field = cls.getField(fieldName);
        Object provalue = field.get(cls);
        return provalue;
	} catch (Exception ex) {
		//handleReflectionException(ex);
		return null;
	}
}
/**
 * Get specify private field value with the given the name of field
 * @param obj the target object
 * @param fieldName the name of field
 * @return the field value if exist
 */
public Object getPrivateFieldValue(Object obj, String fieldName) {
	try {
        Class<?> cls = obj.getClass();
        Field field = cls.getDeclaredField(fieldName);
        field.setAccessible(true);
        Object retvalue = field.get(obj);
        return retvalue;
	} catch (Exception ex) {
		handleReflectionException(ex);
		return null;
	}
}

/**
 * Get method
 * @param clsName  the class to introspect
 * @param methodName the name of method
 * @param types the type of parameters 
 * @return the method object if exist
 */
public static Method getMethod(String clsName, String methodName, Class<?>... types){
	try {
		Class<?> cls = Class.forName(clsName);
		return cls.getMethod(methodName, types);
	} catch (Exception e) {
		//handleReflectionException(ex);
		return null;
	}
}

/**
 * Invoke Method
 * @param obj the target object
 * @param methodName the name of method
 * @param arguments the value of arguments
 * @return the result of invoke method
 */
public static Object invokeMethod(Object obj, String methodName, Object... arguments){
	Class<?> cls = obj.getClass();
	Method method;
	Object result = null;
	try {
		Class<?>[] parameterTypes = null;
		if(arguments!=null){
			parameterTypes = new Class<?>[arguments.length];
			for(int i=0; i<arguments.length; i++){
				parameterTypes[i] = arguments[i].getClass();
			}
		}
		method = cls.getMethod(methodName, parameterTypes);
		result = method.invoke(obj, arguments);
	} catch (Exception ex) {
		ex.printStackTrace();
		//handleReflectionException(ex);
	}
	return result;
}
public static Object invokeMethod(Object obj, String methodName, Class<?>[] types, Object... arguments){
	Class<?> cls = obj.getClass();
	Method method;
	Object result = null;
	try {
		method = cls.getMethod(methodName, types);
		result = method.invoke(obj, arguments);
	} catch (Exception ex) {
		//logger.error("Invoke method error. " + ex.getMessage());
		//handleReflectionException(ex);
	}
	return result;
}
public static Object invokeMethod(Class<?> cls, String methodName, Object... arguments) {
	try {
		Object obj = cls.newInstance();
		return invokeMethod(obj, methodName, arguments);
	} catch (Exception ex) {
		//handleReflectionException(ex);
		return null;
	}
}
public static Object invokeMethod(String className, String methodName, Object... arguments) {
	try {
		Class<?> cls = Class.forName(className);
		return invokeMethod(cls.newInstance(), methodName, arguments);
	} catch (Exception ex) {
		//handleReflectionException(ex);
		return null;
	}
}

/**
 * Invoke static method
 * @param cls the target class
 * @param methodName the name of method
 * @param arguments the value of arguments
 * @return the result of invoke method
 */
public static Object invokeStaticMethod(Class<?> cls, String methodName, Object... arguments) {
	try {
		Class<?>[] parameterTypes = null;
		if(arguments!=null){
			parameterTypes = new Class<?>[arguments.length];
			for(int i=0; i<arguments.length; i++){
				parameterTypes[i] = arguments[i].getClass();
			}
		}
		Method method = cls.getMethod(methodName, parameterTypes);
		return method.invoke(null, arguments);
	}catch (Exception ex) {
		//handleReflectionException(ex);
		return null;
	}
}
public static Object invokeStaticMethod(String className, String methodName, Object... arguments) {
	try {
		Class<?> cls = Class.forName(className);
		return invokeStaticMethod(cls, methodName, arguments);
	}catch (Exception ex) {
		ex.printStackTrace();
		//handleReflectionException(ex);
		return null;
	}
}

public static Object invokeStaticMethod(String className, String methodName, Class<?>[] types , Object... arguments) {
	try {
		Class<?> cls = Class.forName(className);
		return invokeStaticMethod(cls, methodName, types, arguments);
	}catch (Exception ex) {
		//handleReflectionException(ex);
		return null;
	}
}
public static Object invokeStaticMethod(Class<?> cls, String methodName, Class<?>[] types, Object... arguments) {
	try {
		Method method = cls.getMethod(methodName, types);
		return method.invoke(null, arguments);
	}catch (Exception ex) {
		//handleReflectionException(ex);
		return null;
	}
}

public static void setField(Object obj, String fieldName, Object value){
	Class<?> cls = obj.getClass();
	Field field;
	try {
		field = cls.getField(fieldName);
		field.set(obj, value);
	} catch (Exception ex) {
		ex.printStackTrace();
		//logger.error("Invoke method error. " + ex.getMessage());
		//handleReflectionException(ex);
	}
}


/**
 * Action to take on each method.
 */
public interface MethodCallback {

	/**
	 * Perform an operation using the given method.
	 * @param method the method to operate on
	 */
	void doWith(Method method) throws IllegalArgumentException, IllegalAccessException;
}


/**
 * Callback optionally used to filter methods to be operated on by a method callback.
 */
public interface MethodFilter {

	/**
	 * Determine whether the given method matches.
	 * @param method the method to check
	 */
	boolean matches(Method method);
}


/**
 * Callback interface invoked on each field in the hierarchy.
 */
public interface FieldCallback {

	/**
	 * Perform an operation using the given field.
	 * @param field the field to operate on
	 */
	void doWith(Field field) throws IllegalArgumentException, IllegalAccessException;
}


/**
 * Callback optionally used to filter fields to be operated on by a field callback.
 */
public interface FieldFilter {

	/**
	 * Determine whether the given field matches.
	 * @param field the field to check
	 */
	boolean matches(Field field);
}


/**
 * Pre-built FieldFilter that matches all non-static, non-final fields.
 */
public static FieldFilter COPYABLE_FIELDS = new FieldFilter() {

	public boolean matches(Field field) {
		return !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));
	}
};


/**
 * Pre-built MethodFilter that matches all non-bridge methods.
 */
public static MethodFilter NON_BRIDGED_METHODS = new MethodFilter() {

	public boolean matches(Method method) {
		return !method.isBridge();
	}
};


/**
 * Pre-built MethodFilter that matches all non-bridge methods
 * which are not declared on <code>java.lang.Object</code>.
 */
public static MethodFilter USER_DECLARED_METHODS = new MethodFilter() {

	public boolean matches(Method method) {
		return (!method.isBridge() && method.getDeclaringClass() != Object.class);
	}
};
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值