Get generic type of class at runtime

后端 未结 26 2488
野的像风
野的像风 2020-11-21 04:40

How can I achieve this?

public class GenericClass
{
    public Type getMyType()
    {
        //How do I return the type of T?
    }
}
26条回答
  •  囚心锁ツ
    2020-11-21 05:22

    Use Guava.

    import com.google.common.reflect.TypeToken;
    import java.lang.reflect.Type;
    
    public abstract class GenericClass {
      private final TypeToken typeToken = new TypeToken(getClass()) { };
      private final Type type = typeToken.getType(); // or getRawType() to return Class
    
      public Type getType() {
        return type;
      }
    
      public static void main(String[] args) {
        GenericClass example = new GenericClass() { };
        System.out.println(example.getType()); // => class java.lang.String
      }
    }
    

    A while back, I posted some full-fledge examples including abstract classes and subclasses here.

    Note: this requires that you instantiate a subclass of GenericClass so it can bind the type parameter correctly. Otherwise it'll just return the type as T.

提交回复
热议问题