如何创建已知类型的类文字:Class<List<String>> [英] How to create a class literal of a known type: Class<List<String>>
问题描述
采取以下措施:
public Class<List<String>> getObjectType() {
// what can I return here?
}
我可以从这个方法返回什么样的类文字表达式来满足泛型并编译?List.class
不会编译,List.
也不会编译.
What class literal expression can I return from this method which will satisfy the generics and compile? List.class
won't compile, and neither will List.<String>class
.
如果您想知道为什么",我正在编写 Spring 的 FactoryBean<List<String>>
的实现,这需要我实现 Class
.然而,这不是一个 Spring 问题.>getObjectType()
If you're wondering "why", I'm writing an implementation of Spring's FactoryBean<List<String>>
, which requires me to implement Class<List<String>> getObjectType()
. However, this is not a Spring question.
我悲痛的呼声已经被 SpringSource 的权力听到了,所以 Spring 3.0.1 将把 getObjectType()
的返回类型更改为Class>
,巧妙地避免了这个问题.
edit: My plaintive cries have been heard by the powers that be at SpringSource, and so Spring 3.0.1 will have the return type of getObjectType()
changed to Class<?>
, which neatly avoids the problem.
推荐答案
你总是可以投射到你需要的,像这样
You can always cast to what you need, like this
return (Class<List<String>>) new ArrayList<String>().getClass();
或
return (Class<List<String>>) Collections.<String>emptyList().getClass();
但我认为这不是您想要的.好吧,它可以工作,但有警告,但它并不完全漂亮".
But I assume that's not what you are after. Well it works, with a warning, but it isn't exactly "beautiful".
我刚找到这个
为什么通配符参数化类型没有类字面量?
Why is there no class literal for wildcard parameterized types?
因为通配符参数化类型没有精确的运行时类型表示.
Because a wildcard parameterized type has no exact runtime type representation.
所以投射可能是唯一的出路.
So casting might be the only way to go.
这篇关于如何创建已知类型的类文字:Class<List<String>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!