Integer to int using jaxb

*爱你&永不变心* 提交于 2019-12-23 12:09:48

问题


I have a weird situation where the getter in a class returns a primitive int type, and the setter takes a Integer class.

When jaxb unmarshals an element to this class, it cannot find the setter it is looking for:

public class Foo {
    int bar;

    public int getBar() {
        return this.bar;
    }

    public void setBar(Integer bar) {
        this.bar = bar.intValue();
    }
}

I have tried adding:

@XmlElement ( type = java.lang.Integer.class, name = "bar" ) 

to the getter (and the setter), to change the type of the field in schema, but that does not help.

During unmarshalling I get this error: The property has a getter "public int com.example.getBar()" but no setter. For unmarshalling, please define setters.

I can't modify the class, as in, I can't change bar to an Integer or add a new setter with primitive type, but I can add annotations.


回答1:


You can solve this issue by configuring JAXB to use field access. This is done via the @XmlAccessorType annotation:

package forum8334195;

import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {
    int bar;

    public int getBar() {
        return this.bar;
    }

    public void setBar(Integer bar) {
        this.bar = bar.intValue();
    }

    /**
     * Put logic to update domain object based on bar field here.  This method
     * will be called after the Foo object has been built from XML.
     */
    private void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
         System.out.println(bar);
    }

}

For More Information

  • http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html



回答2:


Posting from phone so bear with me! The property doesn't match the javabeans spec so that's the problem, as you probably know. Can you add a new setter/getter pair using a new name, which both use Integer, and put the XML tags on that new property? The new methods would just delegate to the existing ones. HTH




回答3:


It's a real shame you can't introduce any extra methods. If you could add an extra private method, you could do this:

@XmlAccessorType(XmlAccessType.NONE)
public class Foo {
    int bar;

    public int getBar() {
        return this.bar;
    }

    @XmlElement
    private Integer getBar() {
        return this.bar;
    }

    public void setBar(Integer bar) {
        this.bar = bar.intValue();
    }
}

If that doesn't work, you're probably stuck using @XmlJavaTypeAdaptor and XmlAdaptor<Foo, YourAdaptedFoo>, but that's really nasty.



来源:https://stackoverflow.com/questions/8334195/integer-to-int-using-jaxb

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