我正在尝试使用反射包访问私有方法。我能够访问私有方法,但我在发送参数时遇到了问题。
我的代码如下所示:
Sample s = new Sample();
java.lang.reflect.Method method [] = Sample.class.getDeclaredMethods();
System.out.println("Total Number of methods in Sample class"+method.length);
for (int i=0; i<method.length;i++) {
String methodName=method[i].getName();
System.out.println("Method Name is "+methodName);
if (methodName.equalsIgnoreCase("sampleTest1")) {
method[i].setAccessible(true);
//This is calling sampleTest1 method; it's not working
//System.out.println(method[i].invoke(s, new String[]{"ABC"});
} else {
//This is calling sampleTest method and it's working
System.out.println(method[i].invoke(s, null));
}
}
我的示例类:
public class Sample {
private String sampleTest(){
return "Private Method";
}
private String sampleTest1(String abc){
return "Private Method";
}
}
我可以访问 sampleTest() 方法,但我不知道如何将参数传递给 sampleTest1() 方法。你能帮忙吗?
输出
Total Number of methods in Sample class2
Method Name is sampleTest
Exception in thread "main" java.lang.IllegalAccessException: Class com.sarma.reflection.sample.SampleTest can not access a member of class com.sarma.reflection.sample.Sample with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
at java.lang.reflect.Method.invoke(Method.java:588)
at com.sarma.reflection.sample.SampleTest.main(SampleTest.java:26)