Method 类描述的是类对象的方法信息。 其中包含了被反射方法的信息, 访问信息。在运行时, 我们可以通过该类进行方法的调用。
1 获取 Method
1.1 方法
因为 Java 中的 java.lang.reflect 包下所有类的构造函数都不为 public, 同时类都是 final 类型的, 因此, 不能直接通过外部 new 来获取该方法。
获取所有的 public 方法,包括其父类, 接口的
public Method[] getMethods();获取指定参数的 public 方法, 包括其父类, 接口的
public Method getMethod(String name, Class<?>... parameterTypes);获取声明(public, private, protected, friendly)的所有普通方法
public Method[] getDeclaredMethods();获取声明(public, private, protected, friendly)的指定参数的普通方法
public Method getDeclaredMethod(String name, Class<?>... parameterTypes);1.2 实例
该实例称为实例1。
定义父类
public class ParentClass { private String privateMethod(){ return "ParentClass::privateMethod"; } String defaultMethod(){ return "ParentClass::defaultMethod"; } protected String protectedMethod(){ return "ParentClass::protectedMethod"; } public String publicMethod(){ return "ParentClass::public"; } }定义子类
public class ChildClass extends ParentClass { private String childPrivateMethod(){ return "ChildClass::childPrivateMethod"; } String childDefaultMethod(){ return "ChildClass::childDefaultMethod"; } protected String childProtectedMethod(){ return "ChildClass::childProtectedMethod"; } public String childPublicMethod(){ return "ChildClass::childPublicMethod"; }测试类
