获取具有泛型的java.lang.Class [英] Getting a java.lang.Class with generics
问题描述
我是一名学习Java的C#专家,我试图了解泛型在Java中的工作原理.
I'm a C# guy learning Java and I'm trying to understand how generics work in Java.
给出一个类或接口"SomeThing",我知道我可以这样做以获得该类型的类:
Given a class or interface "SomeThing", I know I can do this to get the Class of that type:
Something.class
现在,有了通用接口
我很想写
(GenericInterface<SomeClass>).class
但是编译器不太喜欢.
感谢您的帮助.
推荐答案
这是因为由于进行了擦除,因此不是一个GenericInterface<SomeClass>
类.只有一个GenericInterface
类,它具有一个通用参数.
That's because, thanks to erasure, there isn't a GenericInterface<SomeClass>
class. There's just a GenericInterface
class, which has a generic parameter.
如果需要它,以便可以调用一般的类型安全方法,例如Class.cast()
或Class.newInstance()
,那么您就不走运了.泛型本质上是一个编译时概念.在运行时没有足够的信息来执行常规检查,因此对于任意Class
实例,这些方法 都是类型安全的.
If you want it so that you can call generically type-safe methods such as Class.cast()
or Class.newInstance()
, then you're out of luck. Generics are essentially a compile-time concept; there isn't enough information available at runtime to perform the generic checks, and so these methods can't be type-safe for an arbitrary Class
instance.
在这种情况下,您可以做的最好的事情是使用原始" GenericInterface.class
,然后在之后立即将结果显式转换为GenericInterface<SomeClass>
.这将正确地发出未经检查"的警告,因为如上所述,没有运行时检查可以确定对象确实具有正确的泛型参数,而JVM只需要听话就行.
The best you can do in this case is use the "raw" GenericInterface.class
, then explicitly cast the results into GenericInterface<SomeClass>
immediately afterwards. This will correctly give an "unchecked" warning, since as mentioned above there is no runtime check that the object really has the right generic parameter, and the JVM just has to take your word for it.
(沿着同一行,如果您尝试执行某种instanceof
检查,那么也根本不可能. object 对该类没有通用参数;只有您分配给它的变量才能执行.因此,由于语言的设计限制,这些运行时检查无法简单地进行.)
(Along the same lines, if you're trying to perform some sort of instanceof
check, then that's simply not possible either. An object doesn't have a generic parameter to its class; only the variables you assign it to do. So again, these runtime checks just plain aren't possible due to the design constraints of the language.)
这篇关于获取具有泛型的java.lang.Class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!