如何创建一个已知类型的类文字:Class< List< String>> [英] How to create a class literal of a known type: Class<List<String>>

查看:126
本文介绍了如何创建一个已知类型的类文字: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 $

解决方案

您可以随时投射您需要的内容,如

()
$ b

  return(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 will List.<String>class.

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.

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();

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&lt; List&lt; String&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆