我在我的 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 类必须有一个无参数构造函数。对于没有的 Java 类 构造函数,Java 编译器为该类合成一个无参数构造函数。一旦显式添加构造函数,编译器就不会添加默认的无参数构造函数,因此这里您还必须添加显式无参数构造函数以供 JAXB 的实现使用。
关于Java XML - "1 counts of IllegalAnnotationExceptions",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58040595/