2017-04-12 46 views
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) 

回答

2

变化:

Method privateMethod = c.getMethod("getDetails"); 

到:

Method privateMethod = c.getDeclaredMethod("getDetails"); 
+0

谢谢。现在它的工作 –

相关问题