问题描述
在下面的示例代码中,已使用JAXB字段级访问类型指定了 Employee 类。但是,对于属性 dept ,已使用 @XMLElement 注释在getter方法级别指定了访问类型。
In the example code below, Employee class has been specified with JAXB field level access type. For the property dept, however, the access type has been specified at getter method level with @XMLElement annotation.
在 Organization 类的编组期间,抛出以下异常 -
During marshalling of Organization class, the following exception is thrown -
com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
Class has two properties of the same name "dept"
this problem is related to the following location:
at public java.lang.String com.playground.jaxb.Employee.getDept()
this problem is related to the following location:
at private java.lang.String com.playground.jaxb.Employee.dept
你能帮我理解为什么这个覆盖JAXB访问器类型不起作用吗?此外,任何解决方案都将受到高度赞赏。
Can you help me understand why this overriding of JAXB accessor type is not working please? Also any solution would be highly appreciated.
示例
Root元素类
package com.playground.jaxb;
@XMLRootElement(name="organization")
public class Organization {
@XmlElementWrapper(name = "employees")
@XmlElement(name = "employee")
private Set<Employee> employees;
public Organization{}
// Remainder omitted...
}
员工类
package com.playground.jaxb;
@XMLAccessorType(XMLAccessType.FIELD)
public class Employee {
private String name;
private String dept;
@XMLElement(name="department")
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public Employee {}
// Remainder omitted...
}
推荐答案
您可以重命名getter / setter对,例如 getDept()
- > getDepartment()
You can re-name getter/setter pair, e.g. getDept()
-> getDepartment()
private String dept;
@XmlElement(name="department")
public String getDeptartment() {
return dept;
}
public void setDeptartment(String dept) {
this.dept = dept;
}
但在这种情况下,您将在XML中重复
but in this case you will have duplicate in XML
<dept>my_dept</dept>
<department>my_dept</department>
或者您可以使用 dept a href =http://docs.oracle.com/javaee/5/api/javax/xml/bind/annotation/XmlTransient.html\"rel =nofollow> @ XmlTransient 注释,如果你想改变访问类型吧。
Or you can annotate field dept
with @XmlTransient annotation, if you want to change access type it.
@XmlTransient
private String dept;
@XmlElement(name="department")
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
在这种情况下, dept
字段将被忽略,将使用getter / setter对
In this case, dept
field will be ignored and getter/setter pair will be used instead
这篇关于如何在属性的getter方法上使用@XMLElement覆盖在类级别指定的JAXB @XMLAccessorType(XMLAccessType.FIELD)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!