public class Test8 {
public static void main(String[] args) throws Exception {
Constructor constructor = Person.class.getConstructor(String.class,
int.class);// 通过反射得到Person类带参数构造器
Person person = (Person) constructor.newInstance("张三", 21);// 通过构造器的newInstance方法,传入相应类型的参数得到Person对象
System.out.println("初始化时得值为:" + person.getName() + ","
+ person.getAge());
Method method = person.getClass().getMethod("setName", String.class);// 得到setName方法的Method对象
method.invoke(person, "李四");// 通过invoke反射方法调用setName,对对象赋值
method = person.getClass().getMethod("setAge", int.class);
method.invoke(person, 24);
System.out.println("重新设置后得值为:" + person.getName() + ","
+ person.getAge());
}
/**
* 定义内部类,将其声明为静态,方便main方法访问
*
* @author dell
*
*/
private static class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
|
|