Java泛型。如何正确扩展扩展Generic抽象参数类型类的参数类型类

时间:2015-07-22 08:11:40

标签: java generics inheritance

我有一个通用的抽象超类 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不起作用。发生编译错误。

请帮忙。

1 个答案:

答案 0 :(得分:3)

您需要将Insurance课程声明为

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

然后,您的Liability班级为

public class Liability extends Insurance<Liability> {}