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
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
trueindicates 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
}
}