如何创建一个已知类型的类文字:Class< List< String>> [英] How to create a class literal of a known type: Class<List<String>>
问题描述
public Class< List< String>> getObjectType(){
。
//我可以在这里返回什么?
$ b我可以从这个方法返回什么样的类型文字表达式来满足泛型和编译?
List.class
不会编译,也不会List。< String> class
如果您想知道为什么,我正在编写一个Spring的
FactoryBean< List< String>>
的实现,它要求我实现Class< List< String>> getObjectType()
。然而,这不是一个春天的问题。
编辑:在SpringSource中,所以Spring 3.0.1将返回类型
getObjectType()
更改为Class <?>< / $ c $
解决方案您可以随时投射您需要的内容,如
()
$ breturn(Class< List< String>)new ArrayList< String>()。getClass();
或
return(Class< List< String>>)Collections。< String> emptyList()。getClass();
但我认为这并不是你所追求的。好吧,它的工作,有一个警告,但它不完全是美丽。
我刚发现这个
< blockquote>
为什么通配符参数化类型没有类文字?
因为通配符参数化类型没有确切的运行时类型表示。
所以铸造可能是唯一的选择。
Take the following:
public Class<List<String>> getObjectType() { // what can I return here? }
What class literal expression can I return from this method which will satisfy the generics and compile?
List.class
won't compile, and neither willList.<String>class
.If you're wondering "why", I'm writing an implementation of Spring's
FactoryBean<List<String>>
, which requires me to implementClass<List<String>> getObjectType()
. However, this is not a Spring question.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 toClass<?>
, which neatly avoids the problem.解决方案You can always cast to what you need, like this
return (Class<List<String>>) new ArrayList<String>().getClass();
or
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".
I just found this
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屋!