Java反射 field
-
获取字节码文件对象
Class c = Class.forName(“fieldtest.Student”);
-
通过无参构造方法创建对象obj
Constructor con = c.getConstructor();
Object obj = con.newInstance();
-
通过成员变量名,获取单个的成员变量
Field nameField = c.getField("name");//getField(String name)//Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. //The name parameter is a String specifying the simple name of the desired field
-
将指定对象变量上此 Field 对象表示的字段设置为指定的新值
nameField.set(obj, "y"); // 给obj对象的addressField字段设置值为"y"// public void set(Object obj,Object value)设置与Field对象对应的obj对象中的域的值为value
-
如果想要获取指定私有成员变量
Field ageField = c.getDeclaredField(“age”);
-
取消对私有变量age的访问检查
ageField.setAccessible(true);
-
将指定对象变量上此 Field 对象表示的字段设置为指定的新值
ageField.set(obj, 18);
package fieldtest;public class Student {// 成员变量public String name;// 公共private int age;// 私有// 构造方法public Student() {super();// TODO Auto-generated constructor stub}// 私有构造方法private Student(String name) {this.name = name;}public Student(String name, int age) {super();this.name = name;this.age = age;}// 成员方法(getXxx/setXxx)public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}// 成员方法public void study() {System.out.println("我爱学习java!");}// 私有private void study(String string) {System.out.println("我还爱学习" + string);}@Overridepublic String toString() {return "Student [name=" + name + ", age=" + age + "]";}
}
package fieldtest;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;/** 通过发生获取成员变量并使用*/
public class FieldDemo {public static void main(String[] args) throws Exception {// 获取字节码文件对象Class c = Class.forName("fieldtest.Student");// 获取所有的成员变量System.out.println("获取公共成员变量");Field[] fields = c.getFields();for (Field field : fields) {System.out.println(field);} System.out.println("获取所有成员变量");Field[] fields1 = c.getDeclaredFields();//所有for (Field field : fields1) {System.out.println(field);}/** Person p = new Person(); p.address = "北京"; System.out.println(p);*/// 通过无参构造方法创建对象Constructor con = c.getConstructor();Object obj = con.newInstance();System.out.println(obj);// 通过成员变量名,获取单个的成员变量Field nameField = c.getField("name");//getField(String name) //返回一个 Field对象,它反映此表示的类或接口的指定公共成员字段 类对象。 // public void set(Object obj,Object value)// 将指定对象变量上此 Field 对象表示的字段设置为指定的新值。nameField.set(obj, "y"); // 给obj对象的addressField字段设置值为"y"System.out.println(obj);// 获取age并对其赋值// NoSuchFieldException 私有变量Field ageField = c.getDeclaredField("age");// IllegalAccessException 暴力访问ageField.setAccessible(true);ageField.set(obj, 18);System.out.println(obj);}
}
/*
获取公共成员变量
public java.lang.String fieldtest.Student.name
获取所有成员变量
public java.lang.String fieldtest.Student.name
private int fieldtest.Student.age
Student [name=null, age=0]
Student [name=y, age=0]
Student [name=y, age=18]
*/