我在Java应用程序中运行此代码,第一行抛出一个异常IllegalAnnotationExceptions:
JAXBContext jaxbContext = JAXBContext.newInstance(Product.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(productFound, serverOutput);
我对XML格式不熟悉。因此,根据我在互联网上看到的内容,问题出在Product类,这意味着该文件:
package service;
import javax.xml.bind.annotation.*;
@XmlRootElement(name = "Product")
@XmlAccessorType(XmlAccessType.FIELD)
public class Product {
@XmlElement(name = "id")
private String id;
@XmlElement(name = "name")
private String name;
@XmlElement(name = "price")
private String price;
public Product(String id, String name, String price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
特别是关于注释。
我做错什么了吗 ?还是在我的代码中看起来有些奇怪?
谢谢 !
最佳答案
您的Product类必须具有no-arg构造函数。对于没有的Java类
构造函数,Java编译器为该类综合了一个无参数的参数。显式添加构造函数后,编译器将不会添加默认的no-arg构造函数,因此在这里,您还必须添加显式的no-arg构造函数以供JAXB实现使用。