使用jaxb整数到int [英] Integer to int using jaxb
问题描述
我有一种奇怪的情况,即类中的getter返回一个原始int类型,setter采用Integer类。
I have a weird situation where the getter in a class returns a primitive int type, and the setter takes a Integer class.
当jaxb解组一个元素时class,它找不到它正在寻找的setter:
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();
}
}
我尝试添加:
@XmlElement ( type = java.lang.Integer.class, name = "bar" )
到getter(和setter),以更改架构中字段的类型,但这没有帮助。
to the getter (and the setter), to change the type of the field in schema, but that does not help.
在解组期间我收到此错误:该属性有一个getterpublic int com.example.getBar()但没有setter。对于解组,请定义setter。
During unmarshalling I get this error: The property has a getter "public int com.example.getBar()" but no setter. For unmarshalling, please define setters.
我无法修改类,因为我无法将条形图更改为整数或添加具有基本类型的新setter,但我可以添加注释。
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.
推荐答案
您可以通过配置JAXB以使用字段访问来解决此问题。这是通过 @XmlAccessorType
注释完成的:
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);
}
}
更多信息
- http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html
这篇关于使用jaxb整数到int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!