2010-07-17 81 views
2

动态继承动态继承 - Java

我有一种情况,我想要一个类(这是一个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必须从资源和FeedSnapshot继承,因为两个类都使用JPA连接策略InheritanceType.JOINED,并保存到不同的表从快照必须继承的原因,但是他们都共享共同的属性,我希望他们能够继承这些共同的属性。

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

由于Java不支持多重继承,所以除了使用Embeddable之外,我看不到其他任何方式。

在此先感谢。

回答

2

这里是你如何做到这一点

@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> { 
... 
} 

UPDATE

另一种解决方案可以实现相同的接口(如共同继承无法实现)。在这种情况下,应该在实际的基类上使用@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> { 
... 
} 
+0

谢谢。我在上面的例子中忘记提到的一件事是资源和快照不能扩展“基础”,因为有许多“基础”他们可能不得不延伸。这就是为什么我希望CommonRS可以动态扩展我需要的任何“基础”。 我得出结论,唯一的方法就是使用Embeddable。 – DKD 2010-07-19 13:51:41

+0

尝试实现相同的接口,而不是扩展基类。应该以相同的方式工作 – 2010-07-19 14:48:05

+0

查看最新的答案 – 2010-07-19 15:01:51