Is it possible to use JAXB to unmarshall xml to a specific Java class based on an attribute of the xml?
<shapes>
<shape type="square" points="4" square-specific-attribute="foo" />
<shape type="triangle" points="3" triangle-specific-attribute="bar" />
</shapes>
I would like to have a List of Shape objects containing a triangle and a square, each with their own shape-specific attribute. IE:
abstract class Shape {
int points;
//...etc
}
class Square extends Shape {
String square-specific-attribute;
//...etc
}
class Triangle extends Shape {
String triangle-specific-attribute;
//...etc
}
I’m currently just putting all attributes in one big “Shape” class and it’s less than ideal.
I could get this to work if the shapes were properly named xml elements, but unfortunately I don’t have control of the xml I’m retrieving.
Thanks!
JAXB is a spec, specific implementations will provide extension points to do things such as this. If you are using EclipseLink JAXB (MOXy) you could modify the Shape class as follows:
Then using the MOXy @XMLCustomizer you could access the InheritancePolicy and change the class indicator field from “@xsi:type” to just “type”:
You will need to ensure that you have a jaxb.properties file in with you model classes (Shape, Square, etc) with the following entry specifying the EclipseLink MOXy JAXB implementation:
Below is the rest of the model classes:
Shapes
Square
Triangle
Below is a demo program to check that everything works:
I hope this helps.
For more information on EclipseLink MOXy see:
EDIT
In EclipseLink 2.2 we’re making this easier to configure, check out the following article for more information: