Get actual type of generic type argument on abstract superclass

后端 未结 6 1143
自闭症患者
自闭症患者 2020-11-27 20:08

I have a class like:

public abstract class BaseDao {

  protected Class getClazz() {
     return T.class;
  }

  /         


        
6条回答
  •  無奈伤痛
    2020-11-27 21:06

    If your class is abstract, you can try with this:

    public class getClassOfT() {
        final ParameterizedType type = (ParameterizedType) this.getClass()
                .getGenericSuperclass();
        Class clazz = (Class) type.getActualTypeArguments()[0];
        return clazz;
    }
    

    This only work if the instance is a direct subclass, and the type of the class you want is the first one (see the [0]).

    If you have a large hierarchy of dao's, you can try fidn the BaseDao recursively and get the parametrized type

    See a example here (see the output in the bottom)

    Cheers and sorry for my bad english

提交回复
热议问题