Infinitexistence
Infinitexistence

Reputation: 155

JAX-B annotations for elements that inherit from a parent

When adding JAX-B Java annotations for Java classes - if I have a parent Class Entry, with two children, Book and JournalArticle,

Would I add these annotations for all three classes:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement

ie:

@XmlSeeAlso({au.com.library.Book.class, au.com.library.JournalArticle.class})
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public abstract class Entry implements Serializable{


private static final long serialVersionUID = -1895155325179947581L;

@XmlElement(name="title")
protected String title;
@XmlElement(name="author")
protected String author;
@XmlElement(name="year")
protected int year;

and

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Book extends Entry {

@XmlElement(name="edition")
private String edition;
@XmlElement(name="publisher")
private String publisher;
@XmlElement(name="placeOfPublication")
private String placeOfPub;

and

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class JournalArticle extends Entry {

@XmlElement(name="journalTitle")
private String journalTitle;
@XmlElement(name="volume")
private String volume;
@XmlElement(name="issue")
private String issue;
@XmlElement(name="pageNumbers")
private String pgNumbers;

Upvotes: 1

Views: 1569

Answers (1)

Alex
Alex

Reputation: 25613

The annotation XmlAccessorType can be inherited so I believe it is not mandatory to declare it again on child classes.

@Inherited
@Retention(value=RUNTIME)
@Target(value={PACKAGE,TYPE})
public @interface XmlAccessorType

This is not the case for XmlRootElement, so you will have to annotate each base class with it.

You can find more information on the @Inherited annotation on the javadoc.

Update for your comment:

@Retention(value=RUNTIME) means that the class keeps this annotation even at runtime, that is, a program can use the Java reflection API to check if the annotation is present on a class.

@Target(value={PACKAGE,TYPE}) means that this annotation can be used to annotate classes, interfaces or enums (this is for the value=TYPE), and also at a whole package level (this is for value=PACKAGE). You can see this thread explaining how this can be useful.

More information on the Javadoc:

Upvotes: 1

Related Questions