反映泛型类型参数的方法时的NoSuchMethodException

qiu*_*fei 1 java generics reflection

我发现我在使用泛型类型参数的方法时遇到了问题,但是相同的代码在没有通用类型的参数的情况下工作正常!这是我的代码:

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 -----------");
    }

}
Run Code Online (Sandbox Code Playgroud)

并输出:

-------- 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)
Run Code Online (Sandbox Code Playgroud)

通用型paremeter有什么神奇之处吗?

Yah*_*r10 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);
Run Code Online (Sandbox Code Playgroud)