[英]How to call .class for a class with type parameter? E.g. List<String>.class
To start with an easy example, calling List<String>.class
results in compile error, I can just call List.class
to achieve my purpose. 从一个简单的例子开始,调用List<String>.class
导致编译错误,我可以调用List.class
来实现我的目的。
Recently, I am doing things related to Spring REST template. 最近,我正在做与Spring REST模板相关的事情。 I have to input a class object for the getForObject
method. 我必须为getForObject
方法输入一个类对象。 I have such a class: Foo<T>
. 我有这样一堂课: Foo<T>
。
The result is, I cannot provide Foo<Bar>.class
as one of the arguments. 结果是,我无法提供Foo<Bar>.class
作为参数之一。 Could anyone please help? 有人可以帮忙吗?
You can't do it, because at runtime there are no types, due to type erasure . 你不能这样做,因为在运行时不存在的类型,因为类型擦除 。
When the program executes, there is only List.class
- there is no such thing as List<String>.class
, just provide a List.class
. 当程序执行时,只有List.class
- 没有List<String>.class
这样的东西,只提供一个List.class
。
If you really need to pass the class of the type, change your method to accept a Class<T>
parameter and pass String.class
. 如果确实需要传递类型的类,请更改方法以接受Class<T>
参数并传递String.class
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.