Java泛型.如何正确扩展可扩展通用抽象参数类型的类的参数类型的类 [英] Java Generics. How to properly extend parameter typed class that extends Generic abstract parameter typed class

查看:136
本文介绍了Java泛型.如何正确扩展可扩展通用抽象参数类型的类的参数类型的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有泛型抽象超类 GenericModel ,该类具有我想在子类中调用的方法,如下所示:

I have generic abstract superclass GenericModel with method that I would like to call in children classes as follow:

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;
    }
}

我正在用以下方法扩展该类:

I am extending class this class with:

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

我想扩展该类的内容:Insurance,如下所示:

And I wanna extend class: Insurance with this class as follow:

public class Liability extends Insurance {

}

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

and object of Liability class I would like call method: getByCreationUser_Id() and instead of list of T I would like to get List<Liability> as follow:

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

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

Unfortunatelly I am getting an error:

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

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

When I will call same method on Insurance class it works, I am getting an: List<Insurance>

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

I've already tried declare classes as follow:

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

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

But id doesn't work. Compile errors occur.

请帮助.

推荐答案

您需要将Insurance类声明为

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

然后,您的Liability类为

public class Liability extends Insurance<Liability> {}

这篇关于Java泛型.如何正确扩展可扩展通用抽象参数类型的类的参数类型的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆