2012-08-17 56 views
1

我發現我在使用泛型類型參數方法反映方法時遇到問題,但是相同的代碼可以正常使用沒有泛型類型參數的方法!這裏是我的代碼:NoSuchMethodException當在通用類型參數方法上反映方法

public class Test { 

    public static void method1(Integer i) { 
    } 

    public static void method2(List<Integer> i) { 
    } 

    public static void main(String[] args) throws Exception { 

     Integer i = 5; 
     List<Integer> iList = new ArrayList<Integer>(); 
     Method method1 = Test.class.getDeclaredMethod("method1", i.getClass()); 
     method1.invoke(Test.class, i); 
     System.err.println("-------- method 1 ok -----------"); 
     Method method2 = Test.class.getDeclaredMethod("method2", iList.getClass()); 
     method2.invoke(Test.class, iList); 
     System.err.println("-------- method 2 ok -----------"); 
    } 

} 

和輸出:

-------- method 1 ok ----------- 
Exception in thread "main" java.lang.NoSuchMethodException: 
Test.method2(java.util.ArrayList) 
    at java.lang.Class.getDeclaredMethod(Class.java:1954) 
    at Test.main(Test.java:24) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:601) 
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) 

有什麼魔力與泛型類型paremeter?

+2

'iList.getClass'是'ArrayList.class';沒有聲明'method2(ArrayList)'方法。 – oldrinb 2012-08-17 07:53:42

+0

@veer謝謝。我認爲這是擦除 – qiuxiafei 2012-08-17 07:58:50

+1

它不是擦除,它是你通過錯誤類型的參數。變量類型與對象類型不同。 – oldrinb 2012-08-17 08:00:12

回答

4

ArrayList太具體了,您只是將method2定義爲接受List(正如您通常應該那樣)。

嘗試使用List.class

5
Integer i = 5; 
     List<Integer> iList = new ArrayList<Integer>(); 
     Method method1 = Test.class.getDeclaredMethod("method1", i.getClass()); 
     method1.invoke(Test.class, i); 
     System.err.println("-------- method 1 ok -----------"); 
     Method method2 = Test.class.getDeclaredMethod("method2", 
       List.class); 
     method2.invoke(Test.class, iList); 
相關問題