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

来源:互联网 发布:html网页源码下载 编辑:程序博客网 时间:2024/06/06 19:28

测试反射调用方法

import java.lang.reflect.Method;class T{public void me2(String s){System.out.println("public method ");}private static void me1(String s,Integer i){System.out.println("this is a private static method and the parameters is: "+s+" "+i);}private void me(String s){System.out.println("this is a private method and the parameters is: "+s);}}public class Test1 {public static void main(String[] args){T t=new T();try{Method method=Class.forName("T").getDeclaredMethod("me", new Class[]{String.class});method.setAccessible(true);method.invoke(t, "test private");Method method1=Class.forName("T").getDeclaredMethod("me1", new Class[]{String.class,Integer.class});method1.setAccessible(true);method1.invoke(T.class, "test static private",1296699761);Method method2=t.getClass().getDeclaredMethod("me2",new Class[]{String.class});//method2.setAccessible(true);method2.invoke(t, "test public");}catch(Exception e){e.printStackTrace();}System.out.println("end!");}}


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!

原创粉丝点击