0
當我嘗試訪問使用反射的私有方法時出現以下錯誤。無法使用Reflection API訪問java中的私有方法
下面是示例代碼,
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)
謝謝。現在它的工作 –