更正AccessibleObject.setAccessible(boolean flag)

来源:互联网 发布:springer数据库 编辑:程序博客网 时间:2024/05/21 06:28
JDK API中的解释
AccessibleObject 类是 Field、Method 和 Constructor 对象的基类。它提供了将反射的对象标记为在使用时取消默认 Java 语言访问控制检查的能力。对于公共成员、默认(打包)访问成员、受保护成员和私有成员,在分别使用 Field、Method 或 Constructor 对象来设置或获得字段、调用方法,或者创建和初始化类的新实例的时候,会执行访问检查。
在反射对象中设置 accessible 标志允许具有足够特权的复杂应用程序(比如 Java Object Serialization 或其他持久性机制)以某种通常禁止使用的方式来操作对象。
setAccessible public void setAccessible(boolean flag)                    throws SecurityException 

将 accessible 标志设置为指示的布尔值,值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查,从而提高了性能。值为 false 则指示反射的对象应该实施 Java 语言访问检查。


API说的很清楚了,仔细理解!对于网上误人的言论,自己要有甄别能力!用法举例:

import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class MethodTest {/** * @param args * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */public static void main(String[] args) throws IllegalArgumentException,IllegalAccessException, InvocationTargetException {Example example = new Example();// Method[] methods = example.getClass().getMethods();//getMethods()与getDeclaredMethods()的区别?!不要忘了Method[] methods = example.getClass().getDeclaredMethods();for (Method m : methods) {System.out.println(m.getName());m.setAccessible(true);//Here it is!m.invoke(example);}}}class Example {private void method_1() {System.out.println("private method_1 executes!");}}// 程序输出如下:// method_1// private method_1 executes!


原创粉丝点击