为什么在使用反射时没有非法访问异常 [英] why no illegalAccessException on using reflection
问题描述
我试图学习反思,我想知道这个问题,为什么没有例外?
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);
}
}
为什么不抛出IllegalAccessException?通过阅读其他书籍,我知道如果尝试获取或设置私有或其他无法访问的字段的值或设置最终字段的值,则可能抛出IllegalAccessException.但是在这里,为什么呢?
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?
推荐答案
在访问可访问对象"(方法,构造函数,字段等)时,将进行反射的访问检查.在这种情况下,您的字段是从允许访问它的类中写入的,因此它可以正常工作.
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.
(顺便说一句:这与Java 7方法句柄明显不同,在Java 7方法句柄中,访问检查是在创建方法句柄时而不是在使用时进行的.您可以使用方法句柄来授予对您拥有的方法的额外访问权限访问,方法是将其传递给通常不具有此访问权限的其他代码.)
(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.)
这篇关于为什么在使用反射时没有非法访问异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!