Inheritance when using JAXB

In this article I would like to present a very simple method to deal with inheritance in case of XML parsing in Java. My goal was to parse an XML document using JAXB. The XML document could look like this:

1
2
3
4
5
6
7
8
  <resource>
    <actions>
      <create ... />
      <read ... />
      <update ... />
      <delete ... />
    </actions>
  </resource>

The element named actions could contain many elements of type action, where, in terms of an object-oriented programming langauge, action is like an abstract super-class. Specific implementations are create, read, update, and delete. As you might guess, this example deals with a model-based software generator for Web interfaces. Using JAXB extremely simplifies parsing of XML. You only have to define Java classes for each XML element. With regard to the example above, we have to define classes for resource but not for actions, because this is only a wrapper for a list of single action elements. We have to define an abstract class named Action as base class for Update, Read, Create, and Delete. Let’s have a look at class Resource:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Resource 
{
	private List<Action> action;
 
	public List<Action> getAction() 
	{
		return action;
	}
 
	@XmlElementWrapper( name = "actions" )
	public void setAction(List<Action> action) 
	{
		this.action = action;
	}
}

How can we define that within the actions element there is not only an element of type action allowed but actually also derived classes? The solution is simple. The following annotation does the trick:

1
2
3
4
5
6
7
8
9
	@XmlElementWrapper( name = "actions" )
	@XmlElements( { 
		@XmlElement( name="create", type = Create.class ),
		@XmlElement( name="read", type = Read.class),
		@XmlElement( name="update", type = Update.class ), 
		@XmlElement( name="delete", type = Delete.class ) } )
	public void setAction(List<Action> action) {
		this.action = action;
	}

You can also define attributes in the abstract class Action:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Action 
{
	private String id;
 
	public String getId() {
		return id;
	}
 
	@XmlAttribute
	public void setId(String id) {
		this.id = id;
	}	
}

Note that this class is not annotated with @XmlRootElement. An example of a derived classes is:

1
2
3
4
5
@XmlRootElement( name = "create" )
public class Create extends Action 
{
   ...
}

Kommentar hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.


*