1

我有一个模型,它由一个带有一个注释属性的接口和一个不重新注释该属性的实现的具体实现器组成。为什么这不能正确解组(使用 MOXy 2.5.0)?我得到了一个正确构造的对象,但该属性从未绑定到 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);            

如果我将 IInterface 更改为抽象类,它可以正常工作 - 抽象类和接口不应该以相同的方式处理吗?这是预期的行为,还是已知问题?

谢谢!

4

1 回答 1

1

oxm.xml

您可以使用 EclipseLink JAXB (MOXy's) 外部绑定文件让 MOXy 认为它IInterface是超类InterfaceImpl而不是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>

演示

以下是在创建JAXBContext. 为了这个演示的目的,我添加了一个getId方法,InterfaceImpl以便我可以展示解组的工作。

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());
    }

}

接口.xml

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

输出

123

了解更多信息

于 2013-06-03T18:08:26.857 回答