1

我发现在使用泛型类型参数反映方法时遇到问题,但是相同的代码适用于没有泛型类型参数的方法!这是我的代码:

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)

泛型类型参数有什么神奇之处吗?

4

2 回答 2

4
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);
于 2012-08-17T07:52:07.733 回答
3

ArrayList 太具体了,您只将 method2 定义为采用 List (通常应该这样做)。

尝试使用 List.class

于 2012-08-17T07:53:02.567 回答