繁体   English   中英

是否有可能检索用于类型标记的通用类型(即Class <T> )在运行时?

[英]Is it possible to retrieve the generic type used for a type token (i.e. Class<T>) at runtime?

Neal Gafter引入了类型标记 (例如Class<String> )。 假设在运行时可以访问Class<String>的实例,是否可以在运行时检索泛型类型( String )?

我正在寻找类似于Method.getGenericReturnType()的东西。

我认为这仅适用于字段/方法。 由于类型擦除,我们在运行时无法获得类特定的泛型类型。 如果您有权上课,似乎可以采取一些措施。 阅读此讨论

与C#不同,泛型在Java运行时不存在。 因此,您不能尝试创建通用类型的实例或尝试在运行时查找通用类型的类型。

听起来您想要的是ParameterizedType

通过思考一个Class和来自它的对象( MethodField ),可以得到这些。 但是,您无法从任何旧的Class对象获取ParameterizedType 您可以从Class实例获得一个实例,该实例表示扩展通用类或接口的类型。

可以使用鲍勃·李(Bob Lee)对Gafter的小工具模式进行的改进:

public class GenericTypeReference<T> {

    private final Type type;

    protected GenericTypeReference() {
        Type superclass = getClass().getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
    }

    public Type getType() {
        return this.type;
    }   

    public static void main(String[] args) {

        // This is necessary to create a Class<String> instance
        GenericTypeReference<Class<String>> tr =
            new GenericTypeReference<Class<String>>() {};

        // Retrieving the Class<String> instance
        Type c = tr.getType();

        System.out.println(c);
        System.out.println(getGenericType(c));

    }

    public static Type getGenericType(Type c) {
        return ((ParameterizedType) c).getActualTypeArguments()[0];
    }

}

上面的代码打印:

java.lang.Class<java.lang.String>
class java.lang.String 

暂无
暂无

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

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