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

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

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


当前回答

我不认为你可以,Java在编译时使用类型擦除,这样你的代码就可以与在泛型之前创建的应用程序和库兼容。

来自Oracle文档:

Type Erasure Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods. Insert type casts if necessary to preserve type safety. Generate bridge methods to preserve polymorphism in extended generic types. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

其他回答

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 A<T> {

    protected Class<T> clazz;

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

    public Class<T> getClazz() {
        return clazz;
    }
}

public class B extends A<C> {
   /* ... */
    public void anything() {
       // here I may use getClazz();
    }
}

它可能对某人有用。你可以使用java.lang.ref.WeakReference; 这种方式:

class SomeClass<N>{
  WeakReference<N> variableToGetTypeFrom;

  N getType(){
    return variableToGetTypeFrom.get();
  }
}

使用返回类类型的抽象方法,然后在该类中使用它,无论在何处扩展泛型类,都必须实现该抽象方法以返回所需的类类型

public class AbsractService<T>{
  public abstract Class<T> getClassType ();
   .......
}

在运行时

class AnimalService extends AbstractService<Animal>{

@Override  
public Class<Animal> getClassType (){
        return Animal.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());
    }
}