I have the following:
class A{
@XmlElement
String name;
//getters and setters
}
and
class B extends A{
@XmlElement
String height;
//getters and setters
}
finally I have
@XmlRootElement
class P{
@XmlElement
List<A> things;
//getters and setters
}
If I do
List<A> l = new ArrayList<A>();
l.add(new B('hello', 20)) //Add new B with height of 20 and name hello
P p = new P();
p.setThings(l); //Set things to list of B's.
and marshal P, I only get the field as part of things and not height.
I know that I can add @XmlSeeAlso(B.class) in A and it will all work.
But the issue is that I don't know all extended classes other than B, as A may be extended on runtime.
How do I dynamically define @XmlSeeAlso on runtime?
This depends on how you are creating your JAXBContext. The newInstance method can be called with an explicit list of all your classes, the documentation for that method also gives a similar example.
Edit: If you know at least the package names of potential jaxb classes you could also create a context given a context path.
If the above is not possible you could also create the list of classes at runtime, based on the object you want to serialize. I think it would be better to try to refactor your code to make this unnecessary. The code below is untested:
Note that
@XmlSeeAlso
can also be annotated on a web service, see this post: http://weblogs.java.net/blog/kohlert/archive/2006/10/jaxws_and_type.htmlThis is useful if your base class doesn't have access to the subclasses (e.g. because they're in a different module), but your web service has.