Is there some direct or indirect way to access a private object from another class?
Well, reflection is really your only hope on this one. It'd be the only way you could inspect an object's fields without caring much for its visibility modifiers.
Entity entity = new Entity();
for(Field f : entity.getClass().getDeclaredFields()) {
try {
f.setAccessible(true);
System.out.println(f.get(entity));
} catch(IllegalAccessException e) {
e.printStackTrace();
}
}
But, I do want to strongly caveat you on resetting the accessibility of the field.
If you're running in a highly concurrent environment, and you disable the accessibility immediately after you're done, you will run into a case in which the accessibility is removed in one thread, as you're about to read it in another, which will lead to a giant, confusing mess.
At that point, the fact that you have visibility modifiers becomes moot, and you would want to just use a part-and-parcel getter instead (or have the field be public
, which makes many feel weird about).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments