Java反射之访问私有属性或方法

AccessibleObject类是Field、Method、和Constructor对象的基类。它提供了将反射的对象标记为在使用时取消默认Java语言访问控制检查的能力。对于公共成员、默认(打包)访问成员、受保护成员和私有成员,在分别使用Field、Method和Constructor对象来设置或获得字段、调用方法,或者创建和初始化类的新实例的时候,会执行访问检查。
当反射对象的accessible标志设为true时,则表示反射的对象在使用时应该取消Java语言访问检查。反之则检查。由于JDK的安全检查耗时较多,所以通过setAccessible(true)的方式关闭安全检查来提升反射速度。
01.import java.lang.reflect.Field;  
02.import java.lang.reflect.Method;  
03.  
04./** 
05. * 用Java反射机制来调用private方法 
06. * @author WalkingDog 
07. * 
08. */  
09.  
10.public class Reflect {  
11.      
12.    public static void main(String[] args) throws Exception {  
13.          
14.        //直接创建对象   
15.        Person person = new Person();  
16.          
17.        Class<?> personType = person.getClass();  
18.          
19.        //访问私有方法   
20.        //getDeclaredMethod可以获取到所有方法,而getMethod只能获取public   
21.        Method method = personType.getDeclaredMethod("say", String.class);  
22.          
23.        //压制Java对访问修饰符的检查   
24.        method.setAccessible(true);  
25.          
26.        //调用方法;person为所在对象   
27.        method.invoke(person, "Hello World !");  
28.          
29.        //访问私有属性   
30.        Field field = personType.getDeclaredField("name");  
31.          
32.        field.setAccessible(true);  
33.          
34.        //为属性设置值;person为所在对象   
35.        field.set(person, "WalkingDog");  
36.          
37.        System.out.println("The Value Of The Field is : " + person.getName());  
38.          
39.    }  
40.}  
41.  
42.//JavaBean   
43.class Person{  
44.    private String name;  
45.      
46.    //每个JavaBean都应该实现无参构造方法   
47.    public Person() {}  
48.      
49.    public String getName() {  
50.        return name;  
51.    }  
52.  
53.    private void say(String message){  
54.        System.out.println("You want to say : " + message);  
55.    }  
56.}  

打印结果:

You want to say : Hello World !
The Value Of The Field is : WalkingDog

原文地址:https://www.cnblogs.com/zhishan/p/2601229.html