Java reflection – impact of setAccessible(true)

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
    }

}

Leave a Comment