反射方法剖析
Class
对象提供以下获取对象的方法(Method
):
- getMethod - 返回类或接口的特定方法,只能是public修饰的方法。
- getDeclaredMethod - 返回类或接口的特定方法。
- getMethods - 返回类或接口的所有public方法,包括父类的public方法。
- getDeclaredMethods - 返回类或接口的所有方法,包括 public、protected、默认(包)访问和 private 方法,但不包括继承的方法。
测试用例
//父类
public class RefFather {
public void refFatherMethod(){
System.out.println("我是父类方法 refFatherMethod");
}
}
//子类
public class RefSon extends RefFather{
private void refSonMethod(){
System.out.println("我是子类方法 refMethod");
}
}
//测试方法
public static void main(String[] args) {
try {
//类的全限定名 即包名+类名
Class<?> clz = Class.forName("main.ref.RefSon");
Object obj = clz.newInstance();
Method refFatherMethod = clz.getMethod("refFatherMethod");
Method refSonMethod = clz.getDeclaredMethod("refSonMethod");
refSonMethod.invoke(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
Method
先看Class.getMethod(String name, Class<?>... parameterTypes)
的源码:
@CallerSensitive
public Method getMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
Method method = getMethod0(name, parameterTypes, true);
if (method == null) {
throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
}
return method;
}
上面源码我们只需要重点解决以下疑问就可