2017-04-12 79 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

謝謝。現在它的工作 –

相關問題