Integer in int using jaxb

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

When jaxb disconnects an element for this class, it cannot find the required parameter that 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 tried to add:

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

to the receiver (and setter) to change the type of the field in the circuit, but this does not help.

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

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

+4
source share
3 answers

You can solve this problem by configuring JAXB to use field access. This is done using 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); } } 

Additional Information

+2
source

Phone wiring, so carry me! The property does not meet the javabeans specification, so there is a problem, as you probably know. Can you add a new setter / getter pair using a new name that uses Integer and puts the XML tags in this new property? New methods are simply delegated to existing ones. NTN

+3
source

This is a real shame; you cannot introduce any additional methods. If you can add an additional private method, you can 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 this does not work, you are probably stuck using @XmlJavaTypeAdaptor and XmlAdaptor<Foo, YourAdaptedFoo> , but it is really nasty.

0
source

Source: https://habr.com/ru/post/1383999/


All Articles