首页 > 代码库 > 通过反射机制直接操作属性

通过反射机制直接操作属性

import java.lang.reflect.Field;

public class InvokeFieldDemo {
    public static void main(String[] args) throws Exception {
        Class<?> cl = null;
        Object obj = null;
        cl = Class.forName(PersonZ.class.getName());
        obj = cl.newInstance();
        Field nameField = null;
        Field ageField = null;
        nameField = cl.getDeclaredField("name");
        ageField = cl.getDeclaredField("age");
        nameField.setAccessible(true);
        nameField.set(obj, "Vonkenmo");
        ageField.setAccessible(true);
        ageField.set(obj, 20);
        System.out.println("name:" + nameField.get(obj));
        System.out.println("age :" + ageField.get(obj));
    }
}

通过反射机制直接操作属性