Java泛型 - 获得类? [英] Java generics - get class?

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

问题描述

我得到一个列表,编程如下: public class MyList< T> 。有什么方法可以使用T变量来获取类的名称(所以我可以从 MyList 中知道T是否是String,Socket等)?



编辑:Nevermind,找到答案 here

't。



长答案

由于泛型的实现方式在Java中,泛型类型T不会保留在运行时。不过,您可以使用私人数据成员:

  public class Foo< T> 
{
private Class< T>类型;

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


I got a list, programmed like this: public class MyList<T>. Is there any way to use the T variable to get the name of class (so I can, from within MyList, know if T is String, Socket, etc.)?

EDIT: Nevermind, found the answer here.

解决方案

Short answer: You can't.

Long answer:

Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:

public class Foo<T> 
{
    private Class<T> type;

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

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

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