1
votes

I have a model that consists of an interface with one annotated property, and a concrete implementor that does not re-annotate the implementation of that property. Why doesn't this unmarshal correctly (using MOXy 2.5.0)? I get a correctly constructed object, but the property is never bound to the XML:

<!-- XML -->
<InterfaceImpl id="5150" />
/**
 * Annotated interface
 */
@XmlRootElement(name="IInterface")
public interface IInterface
{
    @XmlAttribute(name="id")
    public void setId(int id);
}

/**
 * Concrete implementor
 */
@XmlRootElement(name="InterfaceImpl")
public class InterfaceImpl implements IInterface
{
    private int m_id = -1;

    @Override
    public void setId(int id)
    {
        m_id = id;
    }   
}

/**
 * Unmarshal code
 */
File f = new File("src\\resources\\Interface.xml");
JAXBContext context = JAXBContext.newInstance(MY_PATH);
Unmarshaller u = context.createUnmarshaller();
InterfaceImpl i = (InterfaceImpl)u.unmarshal(f);            

If I change IInterface to an abstract class, it works correctly - shouldn't abstract classes and interfaces be handled the same way? Is this expected behavior, or a known issue?

Thanks!

1

1 Answers

1
votes

oxm.xml

You could use EclipseLink JAXB (MOXy's) external binding file to make MOXy think that IInterface is the super class of InterfaceImpl instead of Object.

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="forum16878949">
    <java-types>
        <java-type name="InterfaceImpl" super-type="forum16878949.IInterface"/>
    </java-types>
</xml-bindings>

Demo

Below is how you can specify the mapping document when creating the JAXBContext. For the purpose of this demo I added a getId method to InterfaceImpl so I could show the unmarshalling worked.

package forum16878949;

import java.io.File;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    private static String MY_PATH = "forum16878949";

    public static void main(String[] args) throws Exception {
        /**
         * Unmarshal code
         */
        Map<String, Object> properties = new HashMap<String, Object>(1);
        properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "forum16878949/oxm.xml");
        File f = new File("src/forum16878949/Interface.xml");
        JAXBContext context = JAXBContext.newInstance(MY_PATH, IInterface.class.getClassLoader(), properties);
        Unmarshaller u = context.createUnmarshaller();
        InterfaceImpl i = (InterfaceImpl)u.unmarshal(f);
        System.out.println(i.getId());
    }

}

Interface.xml

<?xml version="1.0" encoding="UTF-8"?>
<InterfaceImpl id="123"/>

Output

123

For More Information