gpt4 book ai didi

java - 动态继承 - Java

转载 作者:行者123 更新时间:2023-11-30 09:54:26 26 4
gpt4 key购买 nike

动态继承

我有一种情况,我希望一个类(它是一个 JPA 实体)能够动态地扩展 A 类或 B 类。我的想法是使用泛型,但看起来泛型不支持这个。例如:


@Entity
public abstract class Resource() {
...
}

@Entity
public abstract class Snapshot() {
...
}

public abstract class CommonRS<R extends Resource, S extends Snapshot> {
/* This is the class that I want to dynamically assign Inheritance to. */
...
}

@Entity
public class FeedResource extends CommonRS<Resource> {
...
}

@Entity
public class FeedSnapshot extends CommonRS<Snapshot> {
...
}

我想这样做的原因是 FeedResource 必须从 Resource 继承,而 FeedSnapshot 必须从 Snapshot 继承,因为这两个类都使用 JPA 连接策略 InheritanceType.JOINED 并且持久保存到不同的表,但是他们都有共同的属性,我希望他们能够继承这些共同的属性。

我知道我可以在 CommonRS 上使用 @Embeddable 并将其嵌入到 FeedResource 和 FeedSnapshot 中。

由于 Java 不支持多重继承,所以除了使用 Embeddable 之外,我看不出有任何其他方法可以做到这一点。

提前致谢。

最佳答案

这是你的做法

@MappedSuperClass
public abstract class Base() {
...
// put your common attributes here
}

@Entity
public abstract class Resource() extends Base{
...
}

@Entity
public abstract class Snapshot() extends Base {
...
}

public abstract class CommonRS<R extends Base> {
...
}

@Entity
public class FeedResource extends CommonRS<Resource> {
...
}

@Entity
public class FeedSnapshot extends CommonRS<Snapshot> {
...
}

更新

另一种解决方案是实现相同的接口(interface)(如果无法实现公共(public)继承)。在这种情况下,@MappedSuperClass 注释应该用在实际的基类上。

@Entity
public abstract class Resource() extends BaseIntf {
...
}

@Entity
public abstract class Snapshot() extends BaseIntf {
...
}

public abstract class CommonRS<R extends BaseIntf> {
...
}

@Entity
public class FeedResource extends CommonRS<Resource> {
...
}

@Entity
public class FeedSnapshot extends CommonRS<Snapshot> {
...
}

关于java - 动态继承 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3271713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com