小编典典

java在运行时获取类的通用类型?

java

我该如何实现?

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

到目前为止,我尝试过的所有操作始终返回类型,Object而不是所使用的特定类型。


阅读 530

收藏
2020-01-10

共1个答案

小编典典

正如其他人所提到的,只有在某些情况下才能通过反射来实现。

如果你确实需要类型,这是通常的(类型安全)解决方法:

public class GenericClass<T> {

     private final Class<T> type;

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

     public Class<T> getMyType() {
         return this.type;
     }
}
2020-01-10