传List.class即可,泛型参数在编译后会被擦除掉,无论List里面是String还是什么别的东西都不会影响获取到那个method,在invoke的时候传的参数对不上的话才会产生异常
//Test.java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Test {
public static void main(String[] args) throws InterruptedException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
final Class tmpClass = Tmp.class;
final Method printStrings = tmpClass.getDeclaredMethod("printStrings", List.class);
List strings = Stream.iterate(1, t -> t + 1).limit(10).map(Object::toString).collect(Collectors.toList());
List integers = Stream.iterate(1, t -> t + 1).limit(10).collect(Collectors.toList());
printStrings.invoke(new Tmp(), strings);//正常执行,打出1~10
printStrings.invoke(new Tmp(), integers);//产生异常
}
}
class Tmp {
void printStrings(List strings) {
strings.forEach(System.out::println);
}
}
输出
1
2
3
4
5
6
7
8
9
10
Exception in thread "main" Disconnected from the target VM, address: '127.0.0.1:56752', transport: 'socket'
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at Test.main(Test.java:17)
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at java.util.ArrayList.forEach(ArrayList.java:1249)
at Tmp.printStrings(Test.java:23)
... 5 more
Process finished with exit code 1