I would like to clarify something.
With “plain” Java reflection techniques (without using a library) afaik it is not possible to get a reference to a private field (I mean the java.lang.reflect.Field object, no the field value).
For example, if I have this class:
public class MyClass {
private String field1;
}
If I attempt to execute this:
Field field = MyClass.class.getField("field1");
I will get a NoSuchFieldException exception, as expected.
With the Guava Reflection library, if I try to execute this:
Object o = new MyClass();
Property property = Properties.getPropertyByName(o, "field1");
Field f = property.getField();
I get the following exception:
java.lang.IllegalStateException: Unknown property: field1 in class MyClass
And this was also expected. However, if I add a getter method, like this:
public class MyClass {
private String field1;
public String getField1() {return field1;}
}
Then the Guava-reflection code is working.
I have to confess I am a bit loss about this. I understand that a reflection library could use a getter to return the value of a private instance variable, but the Field object itself just because a getter exists ?. Does someone has an idea how does this happen ?
You can reflect on private fields using standard java reflection, which is probably what Guava is doing under the hood:
getDeclaredFieldallows you to obtain private fields.setAccessibleis needed to prevent security issues.Anyway, as a best practice, consider using reflection on public members only, so work with getters/setters if possible.
Hope that helps.