转:测试反射调用私有方法/私有静态方法

原文:https://blog.csdn.net/zhoudqa/article/details/78256928 

 1 import java.lang.reflect.Method;
 2  
 3 class T{
 4     public void me2(String s){
 5         System.out.println("public method ");
 6     }
 7     private static void me1(String s,Integer i){
 8         System.out.println("this is a private static method and the parameters is: "+s+" "+i);
 9     }
10     private void me(String s){
11         System.out.println("this is a private method and the parameters is: "+s);
12     }
13 }
14 public class Test1 {
15     public static void main(String[] args){
16         T t=new T();
17         try{
18             Method method=Class.forName("T").getDeclaredMethod("me", new Class[]{String.class});
19             method.setAccessible(true);
20             method.invoke(t, "test private");
21             Method method1=Class.forName("T").getDeclaredMethod("me1", new Class[]{String.class,Integer.class});
22             method1.setAccessible(true);
23             method1.invoke(T.class, "test static private",1296699761);
24             Method method2=t.getClass().getDeclaredMethod("me2",new Class[]{String.class});
25             //method2.setAccessible(true);
26             method2.invoke(t, "test public");
27             }catch(Exception e){
28                 e.printStackTrace();
29             }
30         System.out.println("end!");
31     }
32 }

 

getDeclaredMethod方法第一个参数是方法名,第二个是参数类型的数组

invoke方法第一个参数是类或者对象实例,后面的参数是方法形参

setAccessible要设置成true的,否则无法调用private方法 #######  主要是这句

运行结果:

this is a private method and the parameters is: test private
this is a private static method and the parameters is: test static private 1296699761
public method 
end!
---------------------
作者:zhoudqa
来源:CSDN
原文:https://blog.csdn.net/zhoudqa/article/details/78256928
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2018-10-26 13:55  mumu122  阅读(977)  评论(0编辑  收藏  举报