我怎样才能做到这一点呢?

public class GenericClass<T>
{
    public Type getMyType()
    {
        //How do I return the type of T?
    }
}

到目前为止,我所尝试的一切总是返回Object类型,而不是使用的特定类型。


当前回答

泛型在运行时不会具体化。这意味着信息在运行时不存在。

在向Java中添加泛型的同时保持向后兼容性是一项壮举(您可以看到关于它的开创性论文:让未来对过去更加安全:向Java编程语言添加泛型)。

关于这个问题有丰富的文献,有些人对目前的状态不满意,有些人说实际上这是一个诱惑,没有真正的需要。你可以阅读这两个链接,我发现它们很有趣。

其他回答

我做了相同的@Moesio上面,但在Kotlin可以这样做:

class A<T : SomeClass>() {

    var someClassType : T

    init(){
    this.someClassType = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<T>
    }

}

正如其他人提到的,只有在特定的情况下通过反思才有可能。

如果你真的需要这个类型,这是常见的(类型安全的)变通模式:

public class GenericClass<T> {

     private final Class<T> type;

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

     public Class<T> getMyType() {
         return this.type;
     }
}

Java泛型大多是在编译时,这意味着类型信息在运行时丢失。

class GenericCls<T>
{
    T t;
}

会被编译成什么样子

class GenericCls
{
   Object o;
}

要在运行时获得类型信息,必须将其作为ctor的参数添加。

class GenericCls<T>
{
     private Class<T> type;
     public GenericCls(Class<T> cls)
     {
        type= cls;
     }
     Class<T> getType(){return type;}
}

例子:

GenericCls<?> instance = new GenericCls<String>(String.class);
assert instance.getType() == String.class;

使用番石榴。

import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;

public abstract class GenericClass<T> {
  private final TypeToken<T> typeToken = new TypeToken<T>(getClass()) { };
  private final Type type = typeToken.getType(); // or getRawType() to return Class<? super T>

  public Type getType() {
    return type;
  }

  public static void main(String[] args) {
    GenericClass<String> example = new GenericClass<String>() { };
    System.out.println(example.getType()); // => class java.lang.String
  }
}

不久前,我在这里发布了一些完整的示例,包括抽象类和子类。

注意:这需要实例化GenericClass的一个子类,这样它才能正确地绑定类型参数。否则它只会返回类型为T。

public abstract class AbstractDao<T>
{
    private final Class<T> persistentClass;

    public AbstractDao()
    {
        this.persistentClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }
}