我很清楚,通过使用反射可以轻松访问 Java 中的私有(private)字段。如帖子中所示 How to read the value of a private field from a different class in Java?而且有很多。
要实现这一目标,关键一步是设置可访问性。
Field f = obj.getClass().getDeclaredField("aaa");
f.setAccessible(true);
但就我而言,情况是这样的:
class A{
private B b;
class B{
private String value;
}
}
我想在另一个类中获取 a.b.value 的值。当我尝试时,我打算这样做
A obj = createInstanceA();
Field f = obj.getClass().getDeclaredField("b");
f.setAccessible(true);
A.B b = f.get(obj);
Field f2 = b.getClass().getDeclaredField("value");
f2.setAccessible(true);
String value = f2.get(b);
这不起作用,因为 B 无法从 A 中声明出来。 如果A类无法修改,我还有其他选择吗?
最佳答案
你已经这样做了,
public class A {
private B b = new B();
class B {
private String value = "String";
}
}
public class ClassB {
public static void main(String args[]) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
A obj = new A();
Field f = obj.getClass().getDeclaredField("b");
f.setAccessible(true);
A.B b = (B) f.get(obj);
Field f2 = b.getClass().getDeclaredField("value");
f2.setAccessible(true);
String value = (String) f2.get(b);
System.out.println(value);
}
}
您缺少的是 setAccessible(true) 到内部类字段。
关于java - 如何使用Java访问另一个类的私有(private)字段中的私有(private)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59066916/