2012-08-17 58 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); 
相关问题