一、Field
(1)Field
/** * Field: 分装了字段的信息 * 1. 获取字段 * 1.1 Field[] fields = clazz.getDeclaredFields(); * 1.2 Field field = clazz.getDeclaredField("name"); * * 2. 获取指定对象的指定字段的值 * public Object get(Object obj) * obj 为字段所在对象 * 3. 设置指定对象的指定字段的值 * public void set(Object obj, Object value) * obj 字段所在对象 * value 要设置的值 */ @Test public void test10() throws Exception { Class clazz = Class.forName("com.wang.reflection.Person"); //1.获取字段 //1.1 获取Field的数组 Field[] fields = clazz.getDeclaredFields(); for(Field field : fields) { System.out.println("1.1 " + field); } //1.2 获取指定名字的Field Field field = clazz.getDeclaredField("name"); System.out.println("1.2 " + field.getName()); //2.获取指定对象的Field的值 Person person = new Person("AAA", 22); Object val = field.get(person); System.out.println("2 " + val); //3. 设置指定对象的Field值 field.set(person, "BBB"); System.out.println("3 " + person.getName()); //4. 若该字段是私有的,需要调用 Field field2 = clazz.getDeclaredField("age"); field2.setAccessible(true); System.out.println("4 " + field2.get(person)); }
结果输出:
(2)为私有属性赋值
@Test public void test11() throws Exception { String className = "com.wang.reflection.Student"; String fieldName = "age"; Object val = 20; //创建className所对应的对象,并为其fieldName赋值为val Object obj = null; Class clazz = Class.forName(className); Field field = null; for(Class clazz2 = clazz; clazz2 != Object.class; clazz2 = clazz2.getSuperclass()) { try { field = clazz2.getDeclaredField(fieldName); } catch (Exception e) {} } obj = clazz.newInstance(); field.setAccessible(true); field.set(obj, val); Student stu = (Student)obj; System.out.println(stu.getAge()); }
二、Constructor
/** * Constructor: 构造器 */ @Test public void test12() throws Exception { String className = "com.wang.reflection.Person"; Class clazz = Class.forName(className); //1. 获取构造器对象 //1.1 获取所有构造器 Constructor[] constructors = (Constructor []) Class.forName(className).getConstructors(); for(Constructor cons : constructors) { System.out.println("1.1 " + cons); } //1.2 获取指定的构造器 Constructor constructor = clazz.getConstructor(String.class,Integer.class); System.out.println("1.2 " + constructor); //2. 调用构造器的newInstance方法创建对象 Object obj = constructor.newInstance("AAA", 18); }
输出:
1. Java基础--反射之Class类
2. Java基础--反射之Method
3. Java基础--反射之Field ----当前----