[英]Get the number of generic type parameters of a class using its instance?
Is it possible to get the number of type parameters a class has/accepts in Java using its instance?是否可以使用其实例获取类在 Java 中具有/接受的类型参数的数量? For example,例如,
Map<String, Integer> s = new HashMap<>();
int numParams = getNumOfTypeParameters(s); // Should return 2
I know that due to type erasure we can't get the type of these parameters but can we also not get the number of parameters?我知道由于类型擦除我们无法获得这些参数的类型,但我们也无法获得参数的数量吗?
It's as simple as就这么简单
System.out.println(Map.class.getTypeParameters().length); // 2
System.out.println(Class.class.getTypeParameters().length); // 1
System.out.println(Object.class.getTypeParameters().length); // 0
Just look at the documentation for java.lang.Class
and you'l find this .只需查看java.lang.Class
的文档,您就会找到这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.