获取泛型类的泛型参数的类型名称 [英] Get type name for generic parameter of generic class

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

问题描述

在使用泛型时,我在java中遇到了一个小问题。我有一个类 A

  public class A< T> 

A 的方法中,我需要获取 T 的类型名称。
是否有一种方法可以使用 T


找到字符串 s

(如果我创建 A< String> temp = new A< String>(); ,我希望能够获得 java.lang.String - 我必须使用泛型,因为我的一个方法必须返回一个 List< T> )。



这看起来很容易,但我不明白该怎么做。



非常感谢提前寻求帮助。

解决方案

由于 type erasure ,您无法做到这一点。一个 A< String> 的实例不知道 T 的类型。如果您需要它,一种方法是使用类型文字:

  public class A< T> 
{
private final Class< T> clazz中;
$ b $ public A< T>(Class< T> clazz)
{
this.clazz = clazz;
}

//在这里使用clazz
}

然后:

  A< String> x = new A< String>(String.class); 

这很丑陋,但这就是删除的类型:($ / b
$ b

另一种方法是使用Guice的 TypeLiteral 。这是可行的,因为用于指定超类的类型参数没有被删除。 / b>

  A< String> a = new A< String>(){}; 


$ b a 现在引用子类 > A< String> ,因此通过获得 a.getClass()。getSuperClass(),您最终可以返回到字符串,但它非常可怕。


I have a small problem in java while using genericity. I have a class A :

public class A<T>

In a method of A, I need to get the type name of T. Is there a way to find the string s using T ?

(If I create A<String> temp = new A<String>();, I want to be able to get java.lang.String at one point - I have to use genericity because one of my methods will have to return a List<T>).

This seems quite easy but I do not see how to do it.

Thanks a lot in advance for your help.

解决方案

You can't do this in general because of type erasure - an instance of A<String> doesn't know the type of T. If you need it, one way is to use a type literal:

public class A<T>
{
    private final Class<T> clazz;

    public A<T>(Class<T> clazz)
    {
        this.clazz = clazz;
    }

    // Use clazz in here
}

Then:

A<String> x = new A<String>(String.class);

It's ugly, but that's what type erasure does :(

An alternative is to use something like Guice's TypeLiteral. This works because the type argument used to specify a superclass isn't erased. So you can do:

A<String> a = new A<String>() {};

a now refers to a subclass of A<String>, so by getting a.getClass().getSuperClass() you can eventually get back to String. It's pretty horrible though.

这篇关于获取泛型类的泛型参数的类型名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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