代码之家  ›  专栏  ›  技术社区  ›  Isaac

检索泛型参数的类对象

  •  1
  • Isaac  · 技术社区  · 15 年前

    我不确定这是不是重复的问题 this one 主要是因为我对仿制药有点陌生,所以请原谅我。

    我有一个通用类:

    public class MyGeneric<T extends Collection>
    {
        private Class<T> genericType;
    
        public MyGeneric()
        {
            // Missing code here
        }
    }
    

    我的问题是:如何初始化 genericType 属性?基本上,我需要 通用型 接受 Class 任何事物的目标 T 是。如果 T 是一个 LinkedList 我想 通用型 等于 LinkedList.class .

    这有可能吗?我所做的一切似乎都不管用。

    谢谢, 艾萨克

    1 回复  |  直到 15 年前
        1
  •  4
  •   Kirk Woll    15 年前

    你可能不喜欢这个答案,但是你 必须 把它传给你自己。因此,应该声明您的构造函数:

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

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