如何获得泛型类型T的类实例 [英] How to get a class instance of generics type T

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

问题描述

我有一个泛型类, Foo< T> 。在 Foo 的方法中,我想获得类型T的类实例,但我不能调用 T.class

使用 T.class ?避开它的首选方法是什么?

解决方案

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

一个流行的解决方案是将类型参数的 Class 传递给构造函数泛型类型,例如

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

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

$ b $ public void bar(){
//你可以在这里访问typeParameterClass并做任何你喜欢的事情
}
}


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.

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

解决方案

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.

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天全站免登陆