Get generic type of class at runtime

后端 未结 26 2594
野的像风
野的像风 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:00

    This is my solution:

    import java.lang.reflect.Type;
    import java.lang.reflect.TypeVariable;
    
    public class GenericClass {
    
      public static void main(String[] args) {
         for (TypeVariable typeParam : GenericClass.class.getTypeParameters()) {
          System.out.println(typeParam.getName());
          for (Type bound : typeParam.getBounds()) {
             System.out.println(bound);
          }
        }
      }
    }
    

提交回复
热议问题