调用属性,方法,构造器

 

属性调用



@Test
public void fieldCall() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
// 类类型对象
Class<Animal> animalClass = Animal.class;

// 获取指定字段 java.lang.NoSuchFieldException: name 访问失败 字段是private 不推荐使用
//Field name = animalClass.getField("name");

Field name = animalClass.getDeclaredField("name");

// name.set(animal,"阿伟"); 设置异常,需要解放权限访问
// java.lang.IllegalAccessException: Class cn.dai.Reflection.demo.ReflectionTest2 can not access a member of class cn.dai.Reflection.demo.Animal with modifiers "private"
name.setAccessible(false);

// 生成空参对象
Animal animal = animalClass.newInstance();

// 字段实例 调用方法 注入对象和字段注入
name.set(animal,"阿伟");

// 获取对象的此字段
Object o = name.get(animal);
System.out.println(o);
}


 

方法



@Test
public void methodCall() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
// 类类型对象
Class<Animal> animalClass = Animal.class;

// 指定本类的某一方法,第一参数:方法的名字,可变参数,参数列表顺序的参数类型
Method show = animalClass.getDeclaredMethod("show", String.class);

// 生成实例
Animal animal = animalClass.newInstance();

// 以防万一 解开访问权限
show.setAccessible(true);

// 调用方法
Object waKanDa = show.invoke(animal, "瓦坎达");

System.out.println(waKanDa);
}


静态方法调用



@Test
public void staticMethodCall() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
// static void haha(){ System.out.println("adasdasdsad"); }

Class<Animal> animalClass = Animal.class;

Method haha = animalClass.getDeclaredMethod("haha");
haha.setAccessible(true);

// 静态的直接调用运行时类的实例,这里是一个空参方法,只要实例一个参数即可
Object invoke = haha.invoke(animalClass);
}


构造器



@Test
public void constructorCall() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<Animal> animalClass = Animal.class;

// 根据重载的特性,只要参数不一样,或者个数不一样,都可以找到
Constructor<Animal> declaredConstructor = animalClass.getDeclaredConstructor(String.class);

declaredConstructor.setAccessible(true);

// 创建!
Animal animal = declaredConstructor.newInstance("杰哥");
System.out.println(animal);
}