具体类的GenericType

时间:2011-05-27 04:52:13

标签: java generics

如何从我的具体类中获取泛型类型。例如,我有:

class MyClass<String>
{
 public Type getGenericType
 {
      // how can I return String.class in here?
 }
}

我可以用这样的抽象类来做到这一点:

abstract class MyClass<String>
{    
   public Type getGenericType
   {
     Type t = this.getClass().getGenericSuperclass();
     return ((ParameterizedType)t).getActualTypeArguments()[0];
   }
}

如何像抽象类一样对具体类执行类似的操作。如果我不能,你能解释一下为什么吗?

谢谢,

3 个答案:

答案 0 :(得分:2)

你不能这样做,因为一旦代码被编译,泛型甚至不存在
您的String只会变得有效Object

当您的代码在编译后尝试运行时,这显然会导致问题...

答案 1 :(得分:0)

尝试这样的事情:

public class MyClass<T> {

    private final Class<T> type;

    @SuppressWarnings("unchecked")
    public MyClass() {
       type = (Class<T>) this.getClass();
    }

    public Class<T> getGenericType() {
     return type;
    }

}

答案 2 :(得分:0)

在此阶段,Java不支持reification泛型。但是,可以在运行时为字段和方法获取参数类型信息。 This article对此事有很好的洞察力。对于类,通常可以方便地将参数类型显式传递给构造函数:

class ClassWithParameter<T> {
 private final Class<T> parameterType;

 public ClassWithParameter(final Class<T> parameterType) {
      this.parameterType = parameterType;
 }
 ... }

或者,可以创建具有Class属性的自定义运行时注释,并用于注释类,这些类在运行时需要参数类型信息。