我有 2 节课:
public abstract class AbstractTestClass {
private String abstractString = "abstract";
public void showFields() throws IllegalAccessException{
for (Field field : this.getClass().getDeclaredFields()) {
System.out.println(field.get(this));
}
}
}
public class TestClass extends AbstractTestClass {
private String concreteString = "concreteString";
}
并测试:
public class MainTest {
public static void main(String[] args) throws IllegalAccessException{
TestClass test = new TestClass();
test.showFields();
}
}
运行此测试会导致下一个异常:
java.lang.IllegalAccessException: Class AbstractTestClass can not access a member of class TestClass with modifiers "private"
当我调试代码时,它包含 TestClass 的实例。
问题:
- 为什么会这样?
- 如何使此代码工作,而不是使用 Field.setAccessible() 或更改文件的可见性?