Java之反射机制三:获取类的方法
一.实体类BigDog.java
package reflex;
public class BigDog extends Dog {
private Integer age;
public String name;
public BigDog(){}
private void getDog(){}
private BigDog(Integer age, String name) {
this.age = age;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "BigDog{" +
"age=" + age +
'}';
}
}
二.获取类的方法
1.获取类及其父类的公有方法
Class<BigDog> dogClass = BigDog.class; Method[] methods = dogClass.getMethods(); for (Method method : methods) { System.out.println(method); }
运行结果:
2.获取该类的所有方法
Method[] declaredMethods = dogClass.getDeclaredMethods(); for (Method declaredMethod : declaredMethods) { System.out.println(declaredMethod); }
运行结果:
三.获取类的构造方法
Class<BigDog> dogClass = BigDog.class; //获取该类的公有构造方法 Constructor<?>[] constructors = dogClass.getConstructors(); for (Constructor<?> constructor : constructors) { System.out.println(constructor); } //获取该类所有的构造方法(包括有参无参,私有共有) Constructor<?>[] declaredConstructors = dogClass.getDeclaredConstructors(); for (Constructor<?> declaredConstructor : declaredConstructors) { System.out.println(declaredConstructor); }
//获取该类公有的有参构造方法
Constructor<BigDog> constructor = dogClass.getConstructor(Integer.class);
System.out.println(constructor);
//获取该类私有的有参构造方法 Constructor<BigDog> declaredConstructor = dogClass.getDeclaredConstructor(Integer.class, String.class); System.out.println(declaredConstructor);
运行结果:
四.获取该类指定的方法
1.获取类指定的公有方法
//获取ArrayList的add方法 Class<ArrayList> clazz = ArrayList.class; Method method = clazz.getMethod("add", int.class, Object.class); System.out.println(method);
运行结果:
2.获取类指定的私有方法
//获取类的指定私有方法 Class<Object> clazz = Object.class; Method method = clazz.getDeclaredMethod("registerNatives"); System.out.println(method);