- 定义一个Person类,包含私有属性name、age,getXxx和setXxx方法和有参满参构造方法。
- 使用反射的方式创建一个实例、调用构造函数初始化name、age。使用反射方式调用setName方法对姓名进行设置,不使用setAge方法直接使用反射方式对age赋值。
public class Person {
private int age;
private String name;
public Person() {
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
public class Test {
public static void main(String[] args) throws Exception, SecurityException {
Class clas = Person.class;
Constructor constructor = clas.getConstructor(int.class, String.class);
Person person = (Person) constructor.newInstance(38, "马蓉");
System.out.println(person);
Method setName = clas.getMethod("setName", String.class);
setName.invoke(person, "王宝强");
Field age = clas.getDeclaredField("age");
age.setAccessible(true);
age.set(person, 35);
System.out.println(person);
}
}