我有一个泛型抽象超类GenericModel,它带有要在子类中调用的方法,如下所示:

public abstract class GenericModel<T extends GenericModel> {
    @Transient protected Class<T> entityClass;
    public GenericModel() {
    Class obtainedClass = getClass();
    Type genericSuperclass = null;
    for(;;) {
        genericSuperclass = obtainedClass.getGenericSuperclass();
        if(genericSuperclass instanceof ParameterizedType) {
            break;
        }
        obtainedClass = obtainedClass.getSuperclass();
    }
    ParameterizedType genericSuperclass_ = (ParameterizedType) genericSuperclass;
    entityClass = ((Class) ((Class) genericSuperclass_.getActualTypeArguments()[0]));

    // some code

    public List<T> getByCreationUser_Id(Long id) {
        // method body
        return entities;
    }
}


我正在使用以下方法扩展该课程:

public class Insurance extends GenericModel<Insurance> {
     // some code
}


我想用该类扩展类:Insurance,如下所示:

public class Liability extends Insurance {

}


Liability类的对象,我想调用方法:
getByCreationUser_Id(),而不是T的列表,我想得到List<Liability>如下:

List<Liability> currentUserInsurances = new Liability().getByCreationUser_Id(1L);


不幸的是,我收到一个错误:

Type mismatch: cannot convert from List<Insurance> to List<Liability>

当我在保险类上调用相同的方法时,它将起作用:
List<Insurance>

我已经尝试过声明类,如下所示:

public class Insurance<T> extends GenericModel<Insurance<T>> {}
public class Liability extends Insurance<Liability> {}


但是id不起作用。发生编译错误。

请帮忙。

最佳答案

您需要将Insurance类声明为,

public class Insurance<T extends Insurance> extends GenericModel<T> {}


然后,您的Liability类为

public class Liability extends Insurance<Liability> {}

08-18 05:27