【问题标题】:Java XML - "1 counts of IllegalAnnotationExceptions"Java XML - “1 个 IllegalAnnotationExceptions 计数”
【发布时间】:2019-09-21 13:07:05
【问题描述】:

我在我的 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;
    }

}

尤其是关于注释。 我做错什么了吗 ?还是在我的代码中看起来有些奇怪?

谢谢!

【问题讨论】:

    标签: java xml


    【解决方案1】:

    您的 Product 类必须有一个无参数构造函数。对于没有的 Java 类 构造函数,Java 编译器为该类合成一个无参数的。显式添加构造函数后,编译器不会添加默认的无参数构造函数,因此您还必须在此处添加显式无参数构造函数以供 JAXB 的实现使用。

    【讨论】:

    • 好吧,我不知道。现在我修好了它,它可以工作了,非常感谢!!
    【解决方案2】:

    根据您使用的 JAXB 实现,您可能需要向 Product 类添加无参数构造函数,例如:

    public Product() {}
    

    更多信息请参见question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多