JAXB:在超类中声明的字段的注释在子类中有所不同

时间:2017-06-24 13:56:43

标签: java jaxb annotations

我将尝试用一个例子来解释这个问题:

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)是否可以覆盖/添加/在超类中声明的字段的注释?

1 个答案:

答案 0 :(得分:0)

“丑陋”解决方案:

//@SomeXMLAnnotations
public class Derived1 extends Base {

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

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

覆盖/添加属性并注释它们似乎有效。如果从未在某个地方使用过getter或setter,那么它非常难看,因为这必须发生在每个子类中。