简体   繁体   English

如何为类型参数的类调用.class? 例如清单 <String> 。类

[英]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.

相关问题 用于泛型类型的Java转换“.class”-operator,例如列表,到“Class <List <?>>”和“Class <List <Integer >>” - Java casting “.class”-operator used on a generic type, e.g. List, to “Class<List<?>>” and to “Class<List<Integer>>” 可以为标准类提供定制的Jackson序列化程序吗? (例如列表 <List<String> &gt;) - Can there be a custom Jackson serializer for a standard class? (e.g. List<List<String>>) 如何计算出现在Android类中的每种变量类型的数量? 例如int,string等 - How can I count the number each variable type, appears in an Android class? e.g. int, string etc 对泛型类型使用 Class 参数(例如 ArrayList) - Use Class parameter for generic type (e.g ArrayList) Grails ASTTransformation:如何加载其他类(例如Class.forName(..))? - Grails ASTTransformation: how to load other class (e.g. Class.forName(..))? 使用该类是否更有效,例如Hashtable而不是接口,例如Map? - Is it more efficient to use the class, e.g. Hashtable than the interface, e.g. Map? 可以使用反射来获得具体的实现类型(例如Class <? extends MyInterface> )? - Can reflection be used to get a concrete implementing type (e.g. Class<? extends MyInterface>)? 导入自定义类:几个错误(例如,Java:不是语句) - Import of custom class: several errors (e.g. java: not a statement) 类型参数为E的子类的泛型E - Generic class E with type parameter to be a subclass of E 在 Java 正则表达式中,如何获取字符类(例如 [az])以匹配 - 减号? - In a java regex, how can I get a character class e.g. [a-z] to match a - minus sign?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM