13 动态创建对象执行方法
反射的作用
package annotate;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
// 通过反射,动态创建对象
public class Test12 {
public static void main(String[] args) throws Exception {
Class c1 = Body.class;
// 1
Body body = (Body) c1.newInstance(); // 实际上调用类的无参构造
System.out.println(body);
// 2 通过构造器创建对象
Constructor constructor=c1.getConstructor(int.class,int.class,String.class);
Body body1= (Body) constructor.newInstance(18,1,"zhan");
System.out.println(body1);
System.out.println(body1.getAge());
// 通过反射操作私有属性
// body1.age=20; 因为private,不能直接操作
Field age= c1.getDeclaredField("age");
age.setAccessible(true); // 设置为可操作
age.set(body1,20);
System.out.println(body1.getAge());
}
}
class Body{
private int age;
private int id;
private String name;
public Body(){}
public Body(int age, int id, String name) {
this.age = age;
this.id = id;
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age=age;
}
public void say(){}
}