Search code examples
jaxbeclipselinkmoxy

Using MOXy with private XmlAdapters?


I was previously using Sun's RI of JAXB but ran into a bug where I could not use a custom marshaller to marshal to null strings.

I have now switched to MOXy to avoid that issue, but I found that, at least out-of-the-box, MOXy does not handle private XmlAdapters. Rather, it throws an IllegalAccessException. See below for sample code that replicates this.

Is there any way to convince MOXy to use private XmlAdapters, or am I stuck with public ones? I have of course read through the documentation and tried to Google for a solution, but nothing jumped out at me.

@XmlAccessorType(XmlAccessType.FIELD)
@XmlJavaTypeAdapter(StringField.StringFieldAdapter.class)
public class StringField {

    private static final long serialVersionUID = 1L;

    @XmlValue
    private String value;

    public boolean isSet() {
        return value != null;
    }

    public void reset() {
        value = null;
    }

    public String get() {
        return value;
    }

    public void set(String value) {
        this.value = value;
    }

    // N.B - 'non-public' class works with RI, but not with MOXy
    private static class StringFieldAdapter extends XmlAdapter<String, StringField> {

        @Override
        public StringField unmarshal(String v) throws Exception {

            StringField field = new StringField();

            if (v != null) {
                field.set(v);
            }

            return field;
        }

        @Override
        public String marshal(StringField v) throws Exception {

            if (v != null && v.isSet()) {
                return v.get();
            }
            else {
                return null; // Switched to MOXy because this doesn't work in the RI
            }
        }
    }
}

Solution

  • I have been able to reproduce the error that you are seeing. You can track our progress on this issue using the following bug:

    Workaround

    As a workaround you could make the StringFieldAdapter class public.

    public static class StringFieldAdapter extends XmlAdapter<String, StringField> {