package com.reflect;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
@validName
public void setName(String name) {
this.name = name;
}
public void printInfo(String name, int age) {
System.out.println(name + age);
}
public int getAge() {
return age;
}
@MyAge(max = 30, min = 20)
public void setAge(int age) {
this.age = age;
}
}
如果知道反射调用的方法需要传几个参数 直接赋值(参数类型.class? )
Class perClass=Person.class;
String name="reflect";
int age=25;
Object newInstance = perClass.newInstance();
Method method = perClass.getMethod("setName", String.class);
method.invoke(newInstance, name);
System.out.println(name);
Method method2 = perClass.getMethod("printInfo", String.class,int.class);
method2.invoke(newInstance, name,age);
运行结果 如图:
?
|