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?
'iList.getClass'是'ArrayList.class';没有声明'method2(ArrayList)'方法。 – oldrinb 2012-08-17 07:53:42
@veer谢谢。我认为这是擦除 – qiuxiafei 2012-08-17 07:58:50
它不是擦除,它是你通过错误类型的参数。变量类型与对象类型不同。 – oldrinb 2012-08-17 08:00:12