why no illegalAccessException on using reflection

2019-07-20 16:19发布

问题:

i was trying to learn reflection and i across the question, why didn't it have a exception??

public class FieldExceptionTest {
    private boolean b = true;

    public static void main(String[] args) throws Exception{
        FieldExceptionTest ft = new FieldExceptionTest();
        Class<?> c = ft.getClass();
        Field f = c.getDeclaredField("b");
        // f.setAccessible(true); //if i don't write this line, it also can run. 
        f.setBoolean(ft, Boolean.FALSE); 
        System.out.println(ft.b);
    }
}

why did't it throw IllegalAccessException?? By reading other book, i know that An IllegalAccessException may be thrown if an attempt is made to get or set the value of a private or otherwise inaccessible field or to set the value of a final field. But here ,it did't , why?

回答1:

Access checks for reflection happen when the "accessible object" (method, constructor, field, etc.) is accessed. In this case, your field is being written to from a class that is allowed to access it, so it works.

(As an aside: This is distinctly different from Java 7 method handles, where the access check happens when the method handle is created, rather than when it's used. You can use method handles to grant extra access to a method you have access to, by passing it to other code that don't normally have such access.)