【问题标题】:Retrieving the Class object of the generic argument检索泛型参数的 Class 对象
【发布时间】:2010-10-14 23:21:47
【问题描述】:

我不确定这是否是对this one 的重复问题,主要是因为我对泛型有点陌生,所以请见谅。

我有一个通用类:

public class MyGeneric<T extends Collection>
{
    private Class<T> genericType;

    public MyGeneric()
    {
        // Missing code here
    }
}

我的问题是:如何初始化genericType 属性?基本上,我需要genericType 来接收Class 的任何T 对象。如果TLinkedList,我希望genericType 等于LinkedList.class

这有可能吗?我尝试的任何方法似乎都不起作用。

谢谢, 艾萨克

【问题讨论】:

    标签: java generics


    【解决方案1】:

    您可能不会喜欢答案,但您必须自己传递。所以应该声明你的构造函数:

    public MyGeneric(Class<T> genericType)
    {
        this.genericType = genericType;
    }
    

    由于类型擦除,如果没有这样的明确说明,信息将不可用。

    【讨论】:

    • 是的,我开始怀疑类型擦除可能与它有关......另一双眼睛有所帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多