反射机制-访问java属性对象field
创建一个实例对象:student
public class Student { // Field翻译为字段,其实就是属性/成员 // 4个Field,分别采用了不同的访问控制权限修饰符 private String name; // Field对象 protected int age; // Field对象 boolean sex; public int no; public static final double MATH_PI = 3.1415926; }
使用反射机制获取里面的信息:
Class.forName(); 里面的类路径:

public class ReflectTest07 { public static void main(String[] args) throws Exception{ // 使用反射机制,怎么去访问一个对象的属性。(set get) Class studentClass = Class.forName("com.xzit.platfrom.test.Student"); Object obj = studentClass.newInstance(); // obj就是Student对象。(底层调用无参数构造方法) // 获取no属性(根据属性的名称来获取Field) Field noFiled = studentClass.getDeclaredField("no"); // 给obj对象(Student对象)的no属性赋值 /* 虽然使用了反射机制,但是三要素还是缺一不可: 要素1:obj对象 要素2:no属性 要素3:2222值 注意:反射机制让代码复杂了,但是为了一个“灵活”,这也是值得的。 */ noFiled.set(obj, 22222); // 给obj对象的no属性赋值2222 // 读取属性的值 // 两个要素:获取obj对象的no属性的值。 System.out.println(noFiled.get(obj)); // 可以访问私有的属性吗? Field nameField = studentClass.getDeclaredField("name"); // 打破封装(反射机制的缺点:打破封装,可能会给不法分子留下机会!!!) // 这样设置完之后,在外部也是可以访问private的。 nameField.setAccessible(true); // 给name属性赋值 nameField.set(obj, "jackson"); // 获取name属性的值 System.out.println(nameField.get(obj)); } }