Java reflection - impact of setAccessible(true)
java, reflection
Solution
With `setAccessible()` you change the behavior of the `AccessibleObject`, i.e. the `Field` instance, but not the actual field of the class. Here's the documentation (excerpt):
A value of `true` indicates that the reflected object should suppress checks for Java language access control when it is used
And a runnable example:
public class FieldAccessible {
public static class MyClass {
private String theField;
}
public static void main(String[] args) throws Exception {
MyClass myClass = new MyClass();
Field field1 = myClass.getClass().getDeclaredField("theField");
field1.setAccessible(true);
System.out.println(field1.get(myClass)); // no exception
Field field2 = myClass.getClass().getDeclaredField("theField");
System.out.println(field2.get(myClass)); // IllegalAccessException
}
}
Problem
I'm using some annotations to dynamically set values of fields in classes. Since I want to do this regardless of whether it's public, protected, or private, I am a calling `setAccessible(true)` on the Field object every time before calling the `set()` method. My question is what kind of impact does the `setAccessible()` call have on the field itself? More specifically, say it is a private field and this set of code calls `setAccessible(true)`. If some other place in the code was then to retrieve the same field through reflection, would the field already be accessible? Or does the `getDeclaredFields()` and `getDeclaredField()` methods return new instances of a Field object each time? I guess another way of stating the question is if I call `setAccessible(true)`, how important is it to set it back to the original value after I'm done?