java 反射 method操作
method 类:通过反射获得类对象的method对象后,可以对类进行相应操作
***************************
示例
class People{
private String name;
private Integer age;
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 this.getName()+" "+this.getAge();
}
}
public class MyTest5 {
public static void main(String[] args) throws Exception{
Class<?> c=Class.forName("hello2.People");
Method[] methods=c.getDeclaredMethods();
Method[] methods2=c.getMethods();
System.out.println("本类方法:"+Arrays.toString(methods)+"\n");
System.out.println("本类及父类方法:"+Arrays.toString(methods2)+"\n");
for (Method method:methods){
System.out.println(method.toString());
System.out.println(method.toGenericString()+"\n");
}
People people=(People)c.getDeclaredConstructor().newInstance();
Method nameMethod=c.getDeclaredMethod("setName", String.class);
nameMethod.invoke(people,"瓜田李下");
Method ageMethod=c.getDeclaredMethod("setAge",Integer.class);
ageMethod.invoke(people,24);
System.out.println(people.toString());
}
}
*********************
控制台输出
本类方法:[public java.lang.String hello2.People.toString(), public java.lang.String hello2.People.getName(), public void hello2.People.setName(java.lang.String), public java.lang.Integer hello2.People.getAge(), public void hello2.People.setAge(java.lang.Integer)]
本类及父类方法:[public java.lang.String hello2.People.toString(), public java.lang.String hello2.People.getName(), public void hello2.People.setName(java.lang.String), public java.lang.Integer hello2.People.getAge(), public void hello2.People.setAge(java.lang.Integer), public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException, public final void java.lang.Object.wait() throws java.lang.InterruptedException, public boolean java.lang.Object.equals(java.lang.Object), public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll()]
public java.lang.String hello2.People.toString()
public java.lang.String hello2.People.toString()
public java.lang.String hello2.People.getName()
public java.lang.String hello2.People.getName()
public void hello2.People.setName(java.lang.String)
public void hello2.People.setName(java.lang.String)
public java.lang.Integer hello2.People.getAge()
public java.lang.Integer hello2.People.getAge()
public void hello2.People.setAge(java.lang.Integer)
public void hello2.People.setAge(java.lang.Integer)
瓜田李下 24
说明:getMethods()方法可获得本类及父类的所有方法