【问题标题】:Java Generics. How to properly extend parameter typed class that extends Generic abstract parameter typed classJava 泛型。如何正确扩展扩展通用抽象参数类型类的参数类型类
【发布时间】:2015-07-22 08:11:40
【问题描述】:

我有通用抽象超类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&lt;Liability&gt; 如下:

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

很遗憾,我遇到了一个错误:

Type mismatch: cannot convert from List&lt;Insurance&gt; to List&lt;Liability&gt;

当我在 Insurance 类上调用相同的方法时,它会起作用,我得到: List&lt;Insurance&gt;

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

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

但是 id 不起作用。出现编译错误。

请帮忙。

【问题讨论】:

  • 你已经得到了一个很好的答案,我只是想暗示你可能想要避免使用原始类型,所以将你的类声明为 GenericModel>。

标签: java generics inheritance


【解决方案1】:

您需要将Insurance 类声明为,

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

然后,您的Liability 类为,

public class Liability extends Insurance<Liability> {}

【讨论】:

  • 如何为这些类初始化java对象?
  • 好的,但我收到一个错误:来自 JPA 的 Caused by: org.hibernate.InstantiationException: could not instantiate test objectmyInsurance.models.Insurance。你能帮帮我吗?
  • 我认为这与休眠框架有关。而我并不擅长。但它与泛型无关。您可以使用异常跟踪和相关代码提出新问题。确保在其中标记休眠。
  • 我添加了新帖子here。您能告诉我是否可以使用 jpa 持久性将您的答案中的结构/类声明存储在 db 中?
  • 它与 JPA 无关 - 只是 genericSuperclass_.getActualTypeArguments()[0] 现在将为 Insurance 返回一个 TypeVariable - 而不是预期的 Class。我在您的第二个问题中发布了解决方案。
猜你喜欢
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多