当涉及到没有泛型的类时,我可以像这样访问这个 .class 属性:
class Foo{
Class<Foo> getMyClass(){
return Foo.class;
}
}
但是如果 Foo 有一个泛型,我如何访问这个“.class”属性?像这样:
class Foo<T>{
Class<Foo<T>> getMyClass(){
return (Foo<T>).class //this doesnt work...
}
}
我尝试返回Foo.class
,但这行不通: "cannot cast from Class<Foo> to Class<Foo<T>>"
.
我如何访问Foo<T>
类(class)?
最佳答案
您始终可以这样做:
class Foo<T>{
Class<Foo<T>> getMyClass(){
return (Class<Foo<T>>)(Class<?>)Foo.class
}
}
您将收到未经检查的强制转换警告,因为它确实不安全 - 正如其他人提到的,返回的类对象不再是“Foo<T>
的类”,而是“Foo<SomethingElse>
的类”。
关于java - 如何从具有泛型的类访问.class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53700003/