awsome
awsome

Reputation: 2153

alternative to @XmlSeeAlso

abstract Class A{

}


Class B extends A{

}


@XmlRootElement
Class C {
   @XmlElement(name = "tobeserialized")
   A tobeserialized;
}


Class D{
 public void marshal(){
 C all = getData();
 JAXB.marshal(all, new File("saved.xml");

  }

}

for JAXB to know that class B is a subclass of class A, i would need to put a @XmlSeeAlso(value = {B.class}) on Class A. We have around 50 subclasses of A.

But the project dependency is such that Class A lies in a package which cannot access Class B. So I cannot put the annotation on Class A.

what can be the alternatives to look at, so that JAXB can serialize the subclasses of Class A?

Upvotes: 3

Views: 6626

Answers (2)

bdoughan
bdoughan

Reputation: 149037

The @XmlSeeAlso annotation isn't required when mapping an inheritance relationship, but that is when it is most often used. The role of @XmlSeeAlso is to tell JAXB to pull in and produce metadata for classes that can't be inferred from traversing the class.

In your example if you created the JAXBContext on just the C class (JAXBContext.newInstance(C.class)) then the A class would also be processed due to the tobeserialized field, but B wouldn't because there isn't a mechanism in Java to find subclasses. You could solve this by putting @XmlSeeAlso(B.class) on A or by including the subclasses in the classes used to bootstrap the JAXBContext:

JAXBContext.newInstance(B.class, C.class);

Upvotes: 3

Guillaume Darmont
Guillaume Darmont

Reputation: 5018

Been a long time for me, but you may try to add @XmlTransient on class A and @XmlType on class B.

Or @XmlTransient on classes A and B (since they're abstract) and add @XmlType to concrete subclasses.

Upvotes: 0

Related Questions