英文:
Obtain Class instance of Generic interface including type parameters
问题
让我们假设我有一个接口 GenericInterface:
interface GenericInterface<T> {
T get();
}
现在,例如,如果我想获取类型为 Class<GenericInterface<String>> 的类对象,就像这样:
public class Main {
public static void main(String[] args) {
Class<GenericInterface<String>> aClass = ...
}
}
我应该如何做呢?GenericInterface<String>.class 不起作用,而 GenericInterface.class 只返回一个没有类型参数的 Class<GenericInterface>。Class.forName("GenericInterface<java.lang.String>") 也只会抛出 ClassNotFoundException。是否有可能获取这样的对象?
英文:
Lets say i have an Interface GenericInterface
interface GenericInterface<T> {
T get();
}
Now, for example, if I want to obtain a Class object of the type Class<GenericInterface<String>>, like this:
public class Main {
public static void main(String[] args) {
Class<GenericInterface<String>> aClass = ...
}
}
how would I go about doing that? GenericInterface<String>.class doesn't work, and GenericInterface.class only returns a Class<GenericInterface>, without the type parameter. Class.forName("GenericInterface<java.lang.String>") also just throws a ClassNotFoundException. Is it even possible to obtain such an object?
答案1
得分: 2
一方面,由于类型擦除,无法精确表示带参数的类。基本上,GenericInterface<String>.class 与 GenericInterface<Long>.class 是相同的。
另一方面,如果出于某种原因确实需要这样的 Class,仍然可以通过使用双重转换的方式获得(尽管这种方式比较丑陋):
@SuppressWarnings("unchecked")
Class<GenericInterface<String>> cls = (Class<GenericInterface<String>>)(Object)GenericInterface.class;
英文:
On the one hand, because of the type erasure there's no exact representation for parameterized classes. Basically, GenericInterface<String>.class would be the same as GenericInterface<Long>.class.
On the other hand, if you really need such Class for whatever reason, there's still an (ugly) way to have it by using a double cast:
@SuppressWarnings("unchecked")
Class<GenericInterface<String>> cls = (Class<GenericInterface<String>>)(Object)GenericInterface.class;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论