1. 程式人生 > >關於使用JAXB讀取xml文件轉換為java物件出現非法註解異常

關於使用JAXB讀取xml文件轉換為java物件出現非法註解異常

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方法對只有明確標有才會自動繫結。