●Method[] getMethods():返回已加载类声明的所有方法的Method对象数组,包括从父类继承的方法.
●Method getMethod(String name,Class[] paramTypes):返回已加载类声明的所有方法的Method对象,包括从父类继承的方法,参数name指定方法的名称,参数paramTypes指定方法的参数类型.
public static Method getMethod(Object instance, String methodName, Class[] classTypes)
throws NoSuchMethodException ...{
Method accessMethod = getMethod(instance.getClass(), methodName, classTypes);
//参数值为true,禁用访问控制检查
accessMethod.setAccessible(true);
return accessMethod;
}
private static Method getMethod(Class thisClass, String methodName, Class[] classTypes)
throws NoSuchMethodException ...{
if (thisClass == null) ...{
throw new NoSuchMethodException("Error method !");
} try ...{
return thisClass.getDeclaredMethod(methodName, classTypes);
} catch (NoSuchMethodException e) ...{
return getMethod(thisClass.getSuperclass(), methodName, classTypes);
}
}
获得私有方法的原理与获得私有变量的方法相同。当我们得到了函数后,需要对它进行调用,这时我们需要通过 invoke() 方法来执行对该函数的调用,代码示例如下:
//调用含单个参数的方法
public static Object invokeMethod(Object instance, String methodName, Object arg)
throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException ...{
Object[] args = new Object[1];
args[0] = arg;
return invokeMethod(instance, methodName, args);
}
//调用含多个参数的方法
public static Object invokeMethod(Object instance, String methodName, Object[] args)
throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException ...{
Class[] classTypes = null;
&n