package com.itheima.test;
import java.lang.reflect.*;
/*题目:
* 定义一个标准的JavaBean,名叫Person,包含属性name、age。使用反射的方式创建一个实例、调用构造函数初始化name、age,
* 使用反射方式调用setName方法对名称进行设置,不使用setAge方法直接使用反射方式对age赋值
*
* author@张振纲
*/
public class Test5 {
public static void main(String[] args) throws Exception{
Class clazz=Class.forName("com.itheima.test.Person"); //加载字节码文件并创建Class对象
// Constructor c = clazz.getConstructor(String.class,int.class);
Constructor c = clazz.getDeclaredConstructor(String.class,int.class);
Person p =(Person) c.newInstance("zhangsan",19);
System.out.println(p);
Method set = clazz.getMethod("setName",String.class); //通过setName方法设置
set.invoke(p, "lisi");
Field age = clazz.getDeclaredField("age");
// age.set(p, 29);
System.out.println(p);
}
}
class Person{
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
private String name;
private int 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;
}
Person(String name,int age){
this.name=name;
this.age=age;
}
} |