java反射 获取参数名_java
傳List.class即可,泛型參數(shù)在編譯后會(huì)被擦除掉,無(wú)論List里面是String還是什么別的東西都不會(huì)影響獲取到那個(gè)method,在invoke的時(shí)候傳的參數(shù)對(duì)不上的話才會(huì)產(chǎn)生異常
//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);//正常執(zhí)行,打出1~10
printStrings.invoke(new Tmp(), integers);//產(chǎn)生異常
}
}
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
總結(jié)
以上是生活随笔為你收集整理的java反射 获取参数名_java的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 这个红方印多少钱一盒
- 下一篇: Java数组传参sql_Java中如何传