package com.cn;
import java.lang.reflect.Method;
public class Reflect {
/**
* 递归向上(父类)寻找方法
* @param clazz0 目标Class
* @param methodName 方法名称
* @param arg_classes 方法参数Class
* @return Method
* @throws Exception
*/
public static Method getMethod(Class clazz0, String methodName,
final Class[] arg_classes) throws Exception {
Method method = null;
try {
method = clazz0.getDeclaredMethod(methodName, arg_classes);
} catch (NoSuchMethodException e) {
try {
method = clazz0.getMethod(methodName, arg_classes);
} catch (NoSuchMethodException ex) {
if (clazz0.getSuperclass() == null) {
return method;
} else {
method = getMethod(clazz0.getSuperclass(), methodName,
arg_classes);
}
}
}
return method;
}
/**
* @param obj0 目标对象
* @param methodName 方法名
* @param args_classes 方法参数class类型
* @param arg_objects 方法实体参数
* @return
*/
public static Object invoke(final Object obj0, final String methodName,
final Class[] args_classes, final Object[] arg_objects) {
try {
Method method = getMethod(obj0.getClass(), methodName, args_classes);
method.setAccessible(true); // 强制将方法设置成可访问状态(调用private方法)
return method.invoke(obj0, arg_objects);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Object invoke(final Object obj, final String methodName,
final Class[] classes) {
return invoke(obj, methodName, classes, new Object[] {});
}
public static Object invoke(final Object obj, final String methodName) {
return invoke(obj, methodName, new Class[] {}, new Object[] {});
}
}