I am clear that accessing a private field in Java could be easily achieved by using Reflection. As is shown in posts as How to read the value of a private field from a different class in Java? and there are many.
To achieve that , the critical move is to set accessibility.
Field f = obj.getClass().getDeclaredField("aaa");
f.setAccessible(true);
But in my case, the situation is like:
class A{
private B b;
class B{
private String value;
}
}
and I want to get value of a.b.value in another class. When I was trying, I intended to do it as
Field f = obj.getClass().getDeclaredField("b");
f.setAccessible(true);
B b = f.get(obj);
Field f2 = b.getClass().getDeclaredField("value");
String value = f2.get(b);
Which doesn't work out because B could not be declared out of A. Do I have other options if Class A can not be modified?
Aucun commentaire:
Enregistrer un commentaire