Get generic type of class at runtime

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

    If you have a class like:

    public class GenericClass {
        private T data;
    }
    

    with T variable, then you can print T name:

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

提交回复
热议问题