Anas Anas - 3 months ago 25
Java Question

marshaling java objects instantiated from classes which implement interfaces with JAXB

How can we marshal objects into XML files using JAXB when we use interfaces for our classes? I have the following simple classes:

public interface IBook {

public abstract String getName();

public abstract void setName(String name);

}
@XmlRootElement
public class Book implements IBook {

private String name;

@Override
@XmlElement(name ="BookTitle")
public String getName() {
return name;
}

@Override
public void setName(String name) {
this.name = name;
}
}


@XmlRootElement
public class BookStore {

@XmlElement(name ="BookStoreName")
public String name;

@XmlElementWrapper(name ="bookList")
@XmlAnyElement
public HashSet<IBook> books= new HashSet<IBook>();

}


and when I try to marshal an object from BookStore into an XML file, I get the following error:

[com.sun.istack.internal.SAXException2: Weder class de.uni_paderborn.books.Book noch eine der zugehörigen Superklassen ist diesem Kontext bekannt.


javax.xml.bind.JAXBException: Weder class de.uni_paderborn.books.Book noch eine der zugehörigen Superklassen ist diesem Kontext bekannt.]

Sorry for the German error message, but my OS is German. This means that neither the class Book nor one of its superclasses is known in this context! Why do I get such an error?

Answer

Generally to map a field/property that is an interface type you use the type setting on the @XmlElement annotation.

@XmlElementWrapper(name ="bookList")
@XmlElement(type=Book.class, name="book")
public HashSet<IBook> books= new HashSet<IBook>();
Comments