簡體   English   中英

JAXB:在超類中聲明的字段注釋在子類中有所不同

[英]JAXB: Annotations of field declared in superclass differ in subclasses

我將嘗試用一個例子來解釋這個問題:

基礎:

public abstract class Base {
   protected Foo foo;
}

Derived1:

//@SomeXMLAnnotations
public class Derived1 extends Base {
   //Here i would like to define annotations for foo
   @XmlElements({
       @XmlElement(name = "foo1",   type = Foo1.class),
       @XmlElement(name = "foo2",   type = Foo2.class)
   })
   //@AnyAnnoations..
   //protected Foo foo;
}

Derived2的:

//@SomeXMLAnnotations
public class Derived2 extends Base {
   //Here i would like to define annotations for foo too
   //But they will differ from the ones defined in Derived1
   @XmlElements({
       @XmlElement(name = "foo3", type = Foo3.class),
       @XmlElement(name = "foo4", type = Foo4.class)
   })
   //@AnyAnnoations..
   //protected Foo foo;
}

@XmlElements注釋只是一個示例。 它也應該與任何其他注釋一起使用。

我知道我可以遮蓋超類foo字段,但是我認為這不是解決此問題的正確方法。

那么在Java(使用JAXB)中是否可以重寫/向超類中聲明的字段添加注釋?

“丑陋”的解決方案:

//@SomeXMLAnnotations
public class Derived1 extends Base {

   //@AnyAnnoations..
   public Foo getFoo() { 
       return this.foo 
   }

   protected Foo setFoo(Foo foo) { 
       this.foo = foo; 
   }
}

覆蓋/添加屬性並對其進行注釋似乎可行。 如果沒有在任何地方使用getter或setter,那將是非常丑陋的,因為這必須在每個子類中發生。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM