java类如下:
import java.io.Serializable; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; //该注解表示xml文档的根元素 @XmlRootElement public class Book implements Serializable { private static final long serialVersionUID = 2791336442194888575L; // 该注解代表xml文档的element @XmlElement private Integer id; @XmlElement private String name; @XmlElement private String author; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", author=" + author + "]"; } }
错误如下:
Class has two properties of the same name "author" this problem is related to the following location: at public java.lang.String com.yc.bean.Book.getAuthor() at com.yc.bean.Book this problem is related to the following location: at private java.lang.String com.yc.bean.Book.author at com.yc.bean.Book Class has two properties of the same name "id" this problem is related to the following location: at public java.lang.Integer com.yc.bean.Book.getId() at com.yc.bean.Book this problem is related to the following location: at private java.lang.Integer com.yc.bean.Book.id at com.yc.bean.Book Class has two properties of the same name "name" this problem is related to the following location: at public java.lang.String com.yc.bean.Book.getName() at com.yc.bean.Book this problem is related to the following location: at private java.lang.String com.yc.bean.Book.name at com.yc.bean.Book
原因:类中有两个相同的属性名,说明会同时访问getter方法和成员变量
解决办法:
1、在类上加上@XmlAccessorType(XmlAccessType.FIELD)注解,加上此注解那么xml的访问类型为成员变量,而不是getter/setter方法对。
注明:该注解每个非静态,非瞬时成员变量将会被自动绑定到xml文档中,除非标@XmlTransient注解。getter/setter方法只有明确标有JAXB注解才会被绑定。
2、不加@XmlAccessorType(XmlAccessType.FIELD)注解,将@XmlElement注解加到setter或者getter方法上,因为默认的访问类型为getter/setter方法对。
注明:每个public访问权限的getter/sette方法对和公有成员变量才会自动绑定,访问权限为private,protected和缺省访问权限的getter/setter方法对只有明确标有才会自动绑定。