更正AccessibleObject.setAccessible(boolean flag)

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!


  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值