您的位置:首页 > 其它

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

2017-10-17 09:39 483 查看
测试反射调用方法

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!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: