如何获得通用类型T的类实例? [英] How do I get a class instance of generic type T?

查看:68
本文介绍了如何获得通用类型T的类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类Foo<T>.在Foo的方法中,我想获取T类型的类实例,但是我无法调用T.class.

I have a generics class, Foo<T>. In a method of Foo, I want to get the class instance of type T, but I just can't call T.class.

使用T.class绕过它的首选方法是什么?

What is the preferred way to get around it using T.class?

推荐答案

简短的答案是,没有办法找出Java中泛型类型参数的运行时类型.我建议阅读 Java教程中有关类型擦除的章节更多细节.

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. I suggest reading the chapter about type erasure in the Java Tutorial for more details.

对此的一种流行解决方案是将类型参数的Class传递到通用类型的构造函数中,例如

A popular solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

class Foo<T> {
    final Class<T> typeParameterClass;

    public Foo(Class<T> typeParameterClass) {
        this.typeParameterClass = typeParameterClass;
    }

    public void bar() {
        // you can access the typeParameterClass here and do whatever you like
    }
}

这篇关于如何获得通用类型T的类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆