当我尝试使用反射访问私有方法时,我收到以下错误。
以下是示例代码
public class Bank {
public final static String name="Nanda Bank";
public int value;
public double getRatOfInterest(){
return (double) 10.5;
}
private void getDetails(){
System.out.println("User Password 123");
}
}
public class JavaReflectionPrivateExample {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
// getting private method. unable to access private method using reflection api
Class<Bank> c = Bank.class;
Method privateMethod = c.getMethod("getDetails");
privateMethod.setAccessible(true);
privateMethod.invoke(c.newInstance());
}
}
执行JavaReflectionPrivateExample时出现以下异常:
Exception in thread "main" java.lang.NoSuchMethodException:
com.nanda.java.testlab.oops.Bank.getDetails()
at java.lang.Class.getMethod(Unknown Source)
at com.nanda.java.testlab.reflections.JavaReflectionPrivateExample.main(JavaReflectionPrivateExample.java:24)
答案 0 :(得分:2)
变化:
Method privateMethod = c.getMethod("getDetails");
为:
Method privateMethod = c.getDeclaredMethod("getDetails");