21

I have a bunch of JAXB annotated classes that have a field in common, so I moved that field to a super class, like this

public class Base {
    protected SomeType commonField;
}

@XmlRootElement(name = "foo") @XmlType(propOrder = { "commonField", "fooField" })
public class Foo extends Base {
    private SomeOtherType fooField;
}

@XmlRootElement(name = "bar") @XmlType(propOrder = { "commonField", "barField" })
public class Bar extends Base {
    private SomeOtherType barField;
}

Now whenever I marshall one of Foo or Bar I get an IllegalAnnotationException complaining about commonField being listed in propOrder but not present in the class. Removing it from the propOrder annotation everything works fine, but I thougt I was supposed to list all of the mapped fields. What am I missing?

agnul
  • 12,608
  • 14
  • 63
  • 85

1 Answers1

37

The fields/properties from the inherited class will always appear before the fields/properties on the child classes. This means that by default you can not specify them in the propOrder on the child type. If however you mark the parent class as @XmlTransient the fields/properties will be treated as belonging to the child classes and can be included in the propOrder.

bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • 2
    Be aware that this couples the annotation on the subclass to private implementation details of the superclass. Casually refactoring a field name in the superclass, without modifying `propOrder` by hand, will break serialization of the subclass. So will adding a serialized field to the superclass. Also, note that the names in `propOrder` are not the names provided by @XmlElement annotations, but instead are the identifiers of Java fields or properties. [That said, this answer was very helpful to me today.] – Andy Thomas May 19 '16 at 22:29
  • what if Base could be serialized and Foo and bar too? – ics_mauricio Nov 22 '21 at 20:43
  • this help me:note that the names in propOrder are not the names provided by @XmlElement annotations, but instead are the identifiers of Java fields or properties. thanks – Mr Lou Oct 04 '22 at 02:58