gpt4 book ai didi

java - 如何使用反射访问对象中的字段值

转载 作者:IT老高 更新时间:2023-10-28 20:48:55 25 4
gpt4 key购买 nike

我的问题:如何克服 IllegalAccessException 以使用反射访问对象字段的值。

扩展:我正在尝试学习反射,以使我的一些项目更通用。在尝试调用 field.getValue(object) 以获取该对象中该字段的值时,我遇到了 IllegalAccessException。我可以得到名称和输入就好了。

如果我将声明从 private 更改为 public 那么这工作正常。但是为了遵循封装的“规则”,我不想这样做。任何帮助将不胜感激!谢谢!

我的代码:

package main;

import java.lang.reflect.Field;

public class Tester {

public static void main(String args[]) throws Exception {
new Tester().reflectionTest();
}

public void reflectionTest() throws Exception {
Person person = new Person("John Doe", "555-123-4567", "Rover");
Field[] fields = person.getClass().getDeclaredFields();
for (Field field : fields) {
System.out.println("Field Name: " + field.getName());
System.out.println("Field Type: " + field.getType());
System.out.println("Field Value: " + field.get(person));
//The line above throws: Exception in thread "main" java.lang.IllegalAccessException: Class main.Tester can not access a member of class main.Tester$Person with modifiers "private final"
}
}

public class Person {

private final String name;
private final String phoneNumber;
private final String dogsName;

public Person(String name, String phoneNumber, String dogsName) {
this.name = name;
this.phoneNumber = phoneNumber;
this.dogsName = dogsName;
}
}
}

输出:

run:
Field Name: name
Field Type: class java.lang.String
Exception in thread "main" java.lang.IllegalAccessException: Class main.Tester can not access a member of class main.Tester$Person with modifiers "private final"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:95)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:261)
at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:253)
at java.lang.reflect.Field.doSecurityCheck(Field.java:983)
at java.lang.reflect.Field.getFieldAccessor(Field.java:927)
at java.lang.reflect.Field.get(Field.java:372)
at main.Tester.reflectionTest(Tester.java:17)
at main.Tester.main(Tester.java:8)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

最佳答案

在你get一个私有(private)字段之前,你需要在对应的字段上调用setAccessible(true);:

for (Field field : fields) {
field.setAccessible(true); // Additional line
System.out.println("Field Name: " + field.getName());
System.out.println("Field Type: " + field.getType());
System.out.println("Field Value: " + field.get(person));
}

关于java - 如何使用反射访问对象中的字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12784848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com