Note that there are some explanatory texts on larger screens.

plurals
  1. POJAXB xsi:type subclass unmarshalling not working
    text
    copied!<p>I'm following the instructions on using xsi:type from this oft-cited blog post:</p> <p><a href="http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html" rel="nofollow">http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html</a></p> <p>Basically I have this:</p> <pre><code>public abstract class ContactInfo { } public class Address extends ContactInfo { private String street; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } } @XmlRootElement public class Customer { private ContactInfo contactInfo; public ContactInfo getContactInfo() { return contactInfo; } public void setContactInfo(ContactInfo contactInfo) { this.contactInfo = contactInfo; } } </code></pre> <p>And this test:</p> <pre><code>@Test public void contactTestCase() throws JAXBException, ParserConfigurationException, IOException, SAXException { Customer customer = new Customer(); Address address = new Address(); address.setStreet("1 A Street"); customer.setContactInfo(address); JAXBContext jc = JAXBContext.newInstance(Customer.class, Address.class, PhoneNumber.class); StringWriter writer = new StringWriter(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(customer, writer); String s = writer.toString(); System.out.append(s); StringInputStream sis = new StringInputStream(s); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = documentBuilderFactory.newDocumentBuilder(); Document doc = db.parse(sis); Unmarshaller um = jc.createUnmarshaller(); JAXBElement result = um.unmarshal(doc, Customer.class); Customer f = (Customer) result.getValue(); writer = new StringWriter(); marshaller.marshal(customer, writer); s = writer.toString(); System.out.append(s); } </code></pre> <p>And I get this result:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;customer&gt; &lt;contactInfo xsi:type="address" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;street&gt;1 A Street&lt;/street&gt; &lt;/contactInfo&gt; &lt;/customer&gt; javax.xml.bind.UnmarshalException: Unable to create an instance of blog.inheritance.ContactInfo </code></pre> <p>I've tried the default implementation of JAXB, jaxb-impl-2.1.2 and based off this <a href="http://java.net/jira/browse/JAXB-890" rel="nofollow">bug</a>, I've tried jaxb-impl-2.2.6-b38.jar. None of it works.</p> <p>Is this not supposed to work or am I missing some setup?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload