EclipseLink MOXy: Override rules of binding files

落爺英雄遲暮 提交于 2019-12-07 01:53:28

It's a bit odd to map the text property differently on the super and sub classes. If this is something you really want to do, then below is a way you could accomplish this.

Java Model

SuperClass

package forum17982654;

public class SuperClass {

    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}

SubClass

We will override the accessor methods from the super class. This will help us trick MOXy into thinking that SubClass has its own property text.

package forum17982654;

public class SubClass extends SuperClass {

    @Override
    public String getText() {
        return super.getText();
    }

    @Override
    public void setText(String text) {
        super.setText(text);
    } 

}

Metadata

bindings.xml

In the mapping document we will tell MOXy that the real super class of SubClass is java.lang.Object.

<?xml version="1.0"?>
<xml-bindings
    xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
    package-name="forum17982654">
    <java-types>
        <java-type name="SuperClass">
            <xml-root-element/>
            <java-attributes>
                <xml-attribute java-attribute="text"/>
            </java-attributes>
        </java-type>
        <java-type name="SubClass" super-type="java.lang.Object">
            <xml-root-element/>
            <java-attributes>
                <xml-value java-attribute="text"/>
            </java-attributes>
        </java-type>
    </java-types>
</xml-bindings>

Demo Code

Below is some demo code you can run to prove that everything works:

Demo

package forum17982654;

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

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> jaxbContextProperties = new HashMap<String, Object>(1);
        jaxbContextProperties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "bindings.xml");
        JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {SuperClass.class}, jaxbContextProperties);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        StringReader superClassXML = new StringReader("<superClass text='Hello Super Class'/>");
        SuperClass superClass = (SuperClass) unmarshaller.unmarshal(superClassXML);
        System.out.println(superClass.getText());

        StringReader subClassXML = new StringReader("<subClass>Hello Sub Class</subClass>");
        SubClass subClass = (SubClass) unmarshaller.unmarshal(subClassXML);
        System.out.println(subClass.getText());
    }

}

Output

Hello Super Class
Hello Sub Class
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!