在下面的示例代码中,已使用JAXB字段级访问类型指定了 Employee 类。但是,对于属性 dept ,已使用 @XMLElement 注释在getter方法级别指定了访问类型。
在 Organization 类的编组过程中,抛出以下异常 -
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访问器类型不起作用吗?任何解决方案都将受到高度赞赏。
示例
根元素类
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...
}
答案 0 :(得分:2)
您可以重新命名getter / setter对,例如getDept()
- &gt; getDepartment()
private String dept;
@XmlElement(name="department")
public String getDeptartment() {
return dept;
}
public void setDeptartment(String dept) {
this.dept = dept;
}
但在这种情况下,您将在XML中重复
<dept>my_dept</dept>
<department>my_dept</department>
或者,如果要更改访问类型,可以使用@XmlTransient注释对字段dept
进行注释。
@XmlTransient
private String dept;
@XmlElement(name="department")
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
在这种情况下,dept
字段将被忽略,并且将使用getter / setter对