调用运行时类的指定属性
/*
*
*调用运行时类指定结构:属性、方法、构造器
*
*
*@author 刘鑫
*@create by 2021/4/15 10:57
*/
public class ReflectionTest {
/*
如何操作运行时类中的指定的属性
(一般不用此方法,getField(name:"...")要求运行时类中声明的属性为public)
*/
@Test
public void testField() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Constructor constructor = clazz.getConstructor();
Object p = constructor.newInstance();
//获取指定的属性:要求运行时类中声明的属性为public
//通常不采用此方法
Field id = clazz.getField("id");
/*
设置当前属性的值
set():参数1:指明设置哪个对象的属性 参数2:将此属性值设置为多少
*/
id.set(p,1001);
/*
获取当前属性的值
get():参数1:获取哪个对象的当前属性值
*/
int pId = (int) id.get(p);
System.out.println(pId);
}
/*
如何操作运行时类中的指定的属性 --需要掌握
*/
@Test
public void testFiled() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Object obj = clazz.getDeclaredConstructor().newInstance();
Person p = (Person)obj;
//1.getDeclaredField(String fieldName):获取运行时类中指定变量名的属性,能够获取所有修饰符修饰的属性
Field age = clazz.getDeclaredField("age");
//2.若不是public修饰符的属性,得保证当前属性是可访问的
age.setAccessible(true);
//3.获取、设置指定对象的此属性值
age.set(p,1102);
System.out.println(age.get(p));
}
}