如何从具有Generic的类访问.class? [英] How to access the .class from a class with a Generic?
问题描述
对于没有泛型的类,我可以像这样访问这个.class属性:
class Foo {
Class< Foo> getMyClass(){
返回Foo.class;
}
}
但是我如何访问这个.class属性如果Foo有一个通用的?像这样:
class Foo< T> {
Class< Foo< T>> getMyClass(){
return(Foo< T>)class // this does not work ...
}
}
我试图返回 Foo.class
,但这不起作用: 无法从Class< Foo>转换为Class< Foo< T>>
。
>
class Foo< T> {
Class< Foo< T>> getMyClass(){
return(Class< Foo< T>)(Class<>)Foo.class
}
}
您将有未经检查的强制转换警告,因为它确实是不安全的 - 正如其他人所提到的,返回的类对象不再是 Foo< T>
的课程as Foo< SomethingElse>
的课程。
When it comes to classes without generics, i can access this .class attribute like this:
class Foo{
Class<Foo> getMyClass(){
return Foo.class;
}
}
but how do i access this ".class" attribute if Foo has a generic? like this:
class Foo<T>{
Class<Foo<T>> getMyClass(){
return (Foo<T>).class //this doesnt work...
}
}
i have tried to return Foo.class
, but this is not going to work: "cannot cast from Class<Foo> to Class<Foo<T>>"
.
How can i access Foo<T>
's class?
You can always do this:
class Foo<T>{
Class<Foo<T>> getMyClass(){
return (Class<Foo<T>>)(Class<?>)Foo.class
}
}
You will have unchecked cast warnings, because it indeed is unsafe -- as others have mentioned, the returned class object is not any more "Foo<T>
's class" as "Foo<SomethingElse>
's class".
这篇关于如何从具有Generic的类访问.class?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!