简体   繁体   中英

JAXB: Annotations of field declared in superclass differ in subclasses

I will try to explain the issue with an example:

Base:

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;
}

The @XmlElements annotation is just an example. It should work with any other annotation too.

I know I could shadow the superclass foo field but I dont think it's a proper way to solve this issue.

So is it possible in java (with JAXB) to override/add annotation of/to a field that is declared in a superclass?

"Ugly" solution:

//@SomeXMLAnnotations
public class Derived1 extends Base {

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

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

Overriding/adding properties and annotating them seems to work. If getter or setter is never used somewhere it's pretty ugly though, because this has to happen in every subclass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM