无法使用反射API访问java中的私有方法
当我尝试使用反射访问私有方法时,出现以下错误 这是示例代码无法使用反射API访问java中的私有方法,java,reflection,Java,Reflection,当我尝试使用反射访问私有方法时,出现以下错误 这是示例代码 public class Bank { public final static String name="Nanda Bank"; public int value; public double getRatOfInterest(){ return (double) 10.5; } private void getDetails(){ System.ou
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());
}
}
更改:
Method privateMethod = c.getMethod("getDetails");
致:
更改:
Method privateMethod = c.getMethod("getDetails");
致:
Method privateMethod = c.getDeclaredMethod("getDetails");