获取包括类型参数的泛型接口的类实例

huangapple go评论59阅读模式
英文:

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&lt;T&gt; {
    T get();
}

Now, for example, if I want to obtain a Class object of the type Class&lt;GenericInterface&lt;String&gt;&gt;, like this:

public class Main {
    public static void main(String[] args) {
        Class&lt;GenericInterface&lt;String&gt;&gt; aClass = ...
    }
}

how would I go about doing that? GenericInterface&lt;String&gt;.class doesn't work, and GenericInterface.class only returns a Class&lt;GenericInterface&gt;, without the type parameter. Class.forName(&quot;GenericInterface&lt;java.lang.String&gt;&quot;) also just throws a ClassNotFoundException. Is it even possible to obtain such an object?

答案1

得分: 2

一方面,由于类型擦除,无法精确表示带参数的类。基本上,GenericInterface<String>.classGenericInterface<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&lt;String&gt;.class would be the same as GenericInterface&lt;Long&gt;.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(&quot;unchecked&quot;)
Class&lt;GenericInterface&lt;String&gt;&gt; cls = (Class&lt;GenericInterface&lt;String&gt;&gt;)(Object)GenericInterface.class;

huangapple
  • 本文由 发表于 2020年10月2日 21:51:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64172728.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定