繁体   English   中英

获取包含类型参数的 Generic 接口的 Class 实例

[英]Obtain Class instance of Generic interface including type parameters

假设我有一个接口GenericInterface

interface GenericInterface<T> {
    T get();
}

现在,例如,如果我想获取Class<GenericInterface<String>>类型的 Class 对象,如下所示:

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 甚至有可能获得这样的对象吗?

一方面,由于类型擦除,参数化类没有确切的表示。 基本上, GenericInterface<String>.class将与GenericInterface<Long>.class

另一方面,如果您出于某种原因确实需要这样的类,仍然有一种(丑陋的)方法可以通过使用双重转换来获得它:

@SuppressWarnings("unchecked")
Class<GenericInterface<String>> cls = (Class<GenericInterface<String>>)(Object)GenericInterface.class;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM