获取运行时类的方法结构
首先这里我们要通过两个方法来获取运行时类的方法结构
-
Method [] getMethods();
- 获取调用这个方法的运行时类和其父类中所有声明为public权限的方法
- 这个方法的返回值类型为Method
- 这个Method是java中用来表示java中的方法的一个类
-
Method [] getDeclaredMethods()
- 获取调用这个方法的运行时类的所有方法(包括私有方法),但是注意,不包含这个类父类中声明的方法
- 这个方法的返回值也是Method
这里我们通过一个例子来理解如何获取运行时类的方法结构
我们后面的测试程序中使用到了一个自定义类Person,我们先给出自定义类
package 反射.获取运行时类的成员;
import 注解.类型注解.MyAnnotation;
public class Person {
public int age;
protected String sex;
String name;
private int tizhong;
public Person(){
}
public Person(int age ,String sex , String name , int tizhong){
this.age = age;
this.sex = sex;
this.name = name;
this.tizhong = tizhong;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", sex='" + sex + '\'' +
", name='" + name + '\'' +
", tizhong=" + tizhong +
'}';
}
public void eat() throws Exception{
System.out.println("人类吃饭");
System.out.println("人类吃饭");
}
@MyAnnotation
public String play(int x , int y , String z){
return z;
}
//注意: 这个注解我们并没有给定生命周期,这个时候这个注解就默认为"class保留"
@注解.自定义注解.MyAnnotation
protected void see(){
}
private void feel(){
}
}
然后这里我们给出例子(也就是测试程序)
package 反射.获取运行时类的属性结构和内部结构;
import java.lang.reflect.Method;
public class Demo2 {
public static void main(String[] args) {
/*
获取运行时类的方法结构,这个时候会获得Person类中和Person类的父类中所有的声明为public权限的方法
*/
Method [] methods = Person.class.getMethods();
for (Method m1:
methods) {
System.out.println(m1);
}
/*
这个时候我们也是获得运行时类的方法结构,不过这个时候我们获得的是Person类中的所有方法(包括私有方法),但是注意没有父类的方法
*/
Method [] methods1 = Person.class.getDeclaredMethods();
for(Method m2: methods1){
System.out.println(m2);
}
}
}