2014-09-02 36 views
0

如何通過Reflection API調用私有方法?如何在方法參數爲List時通過Reflection調用私有方法?

我的代碼

public class A { 
    private String method(List<Integer> params){ 
     return "abc"; 
    } 
} 

和測試

public class B { 
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { 
     Class<A> clazz = A.class; 
     Method met = clazz.getMethod("method", List.class); 
     met.setAccessible(true); 
     String res = (String) met.invoke("method", new ArrayList<Integer>()); 
     System.out.println(res); 
    } 
} 
+1

那麼,有什麼問題呢?我可以看到一個潛在的問題:爲了調用類的_instance_方法,您需要......以及該類的一個實例。 – Thomas 2014-09-02 14:43:21

回答

5

有在你的代碼中使用getMethod

  • 兩個問題,這隻能返回public方法,讓私房使用getDeclaredMethod
  • 您正在調用"method"文字而不是A類的實例(String沒有此方法,因此您無法在其實例上調用它 - 類似"method".method(yourList)的內容不正確)。

你的代碼看起來應該像

Class<A> clazz = A.class; 
Method met = clazz.getDeclaredMethod("method", List.class); 
//     ^^^^^^^^ 
met.setAccessible(true); 
String res = (String) met.invoke(new A(), new ArrayList<Integer>()); 
//        ^^^^^^^ 
System.out.println(res); 
+0

Bah,他們編輯了一個問題,+1 – 2014-09-02 14:47:28

+0

是的,謝謝。它像一個魅力。 – Alex 2014-09-02 14:53:02

+0

@SotiriosDelimanolis謝謝:) – Pshemo 2014-09-02 14:53:14

相關問題