How do i make an abstract class work with JAXB

一曲冷凌霜 提交于 2019-11-30 20:40:51

Why this is failing is because Jaxb will attempt to create an instance of User. which is abstract and therefore the failure.

On your abstract class add the annotations

@XmlTransient //Prevents the mapping of a JavaBean property/type to XML representation
@XmlSeeAlso({Admin.class, <other class>}) //Instructs JAXB to also bind other classes when binding this class

see the javadoc for each(XmlTransient, XmlSeeAlso)

What this will do is prevent jaxb from trying to initialize your abstract class.

The only downside to this method I found is there will be extra namespace information added to the xml that gets created.

You need to add a XmlSeeAlso annotation to the User class with the attributes Admin and all the other concrete classes that subclass the User class.

@XmlSeeAlso({Admin.class})

PS, don't forget to add the Xml tag @XmlRootElement to the Admin class.

That cannot work, because JAXB has to create new instances (objects) of your classes when unmarshalling the xml. And if a tag from the xml is bound to an abstract class, it just cannot instantiate an object from that class. You either have to make the User class non-abstract or bind the xml tag to a concrete sub-class of User.

Claus Radloff

You have to specify the concrete type of each element:

<user xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Admin">
    ...
</user>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!