Java通过反射获取属性值的步骤如下:

  1. 获取要操作的类的Class对象,可以使用Class.forName()方法或者类的.class属性获取。

  2. 获取要操作的属性的Field对象,可以使用Class类中的getField()、getDeclaredField()方法等。

  3. 设置Field对象的accessible属性为true,这样才能访问非public属性。

  4. 使用Field对象的get()方法获取属性值。

下面是一个示例代码:

public class Person {
    public String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Test {
    public static void main(String[] args) throws Exception {
        Person person = new Person('Tom', 20);
        
        Class clazz = person.getClass();
        Field field = clazz.getDeclaredField('age');
        field.setAccessible(true);
        
        int age = (int) field.get(person);
        System.out.println(age);
    }
}

输出结果为20,表示成功获取了person对象的age属性值。

Java 反射获取属性值:详细步骤及示例代码

原文地址: https://www.cveoy.top/t/topic/nEvx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录