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

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

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


当前回答

如果你有这样一个类:

public class GenericClass<T> {
    private T data;
}

T变量,那么你可以打印T名称:

System.out.println(data.getClass().getSimpleName()); // "String", "Integer", etc.

其他回答

为了完成这里的一些答案,我必须得到MyGenericClass的paramtrizedtype,不管层次结构有多高,在递归的帮助下:

private Class<T> getGenericTypeClass() {
        return (Class<T>) (getParametrizedType(getClass())).getActualTypeArguments()[0];
}

private static ParameterizedType getParametrizedType(Class clazz){
    if(clazz.getSuperclass().equals(MyGenericClass.class)){ // check that we are at the top of the hierarchy
        return (ParameterizedType) clazz.getGenericSuperclass();
    } else {
        return getParametrizedType(clazz.getSuperclass());
    }
}

这里有一个方法,我用过一两次:

public abstract class GenericClass<T>{
    public abstract Class<T> getMyType();
}

随着

public class SpecificClass extends GenericClass<String>{

    @Override
    public Class<String> getMyType(){
        return String.class;
    }
}

一个简单的解决方案,这种出租车如下

public class GenericDemo<T>{
    private T type;

    GenericDemo(T t)
    {
        this.type = t;
    }

    public String getType()
    {
        return this.type.getClass().getName();
    }

    public static void main(String[] args)
    {
        GenericDemo<Integer> obj = new  GenericDemo<Integer>(5);
        System.out.println("Type: "+ obj.getType());
    }
}

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;

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

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

public class GenericClass<T> {

     private final Class<T> type;

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

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