JAVA反射之取消对访问控制检查

来源:互联网 发布:室内设计软件 3d 编辑:程序博客网 时间:2024/05/08 01:28
package test;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;/** * AccessibleObject类是Field、Method、和Constructor对象的基类。它提供了将反射的对象标记为在使用时取消默认Java * 语言访问控制检查的能力。对于公共成员、默认(打包)访问成员、受保护成员和私有成员,在分别使用Field、Method和 * Constructor对象来设置或获得字段、调用方法,或者创建和初始化类的新实例的时候,会执行访问检查。 *  * 当反射对象的accessible标志设为true时,则表示反射的对象在使用时应该取消Java语言访问检查。反之则检查。由于 * JDK的安全检查耗时较多,所以通过setAccessible(true)的方式关闭安全检查来提升反射速度 * @author user * */public class ReflectTest {public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {Person person = new Person();Class<?> personType = person.getClass();//getDeclaredMethod可以获取到所有方法,而getMethod只能获取public  Field field = personType.getDeclaredField("name");//取消对访问控制修饰符的检查field.setAccessible(true);field.set(person, " ZHANG SAN ");System.out.println("The value of the Field is : " + person.getName());Method method = personType.getDeclaredMethod("say", String.class);method.setAccessible(true);method.invoke(person, "Hello World!");}}class Person{private String name;public Person(){};public String getName(){return name;}private void say(String message){System.out.println("Name:"+name+"; say:"+message);}}

0 0