将 JAXB 与 AutoValue 结合使用时出现编组错误 "does not have a no-arg default constructor"

Marsheling error "does not have a no-arg default constructor" when using JAXB with AutoValue

鉴于以下 class:

@XmlRootElement(name = "Person")
@AutoValue
@CopyAnnotations
public abstract class Person {

  @XmlElement
  abstract String name();

  public static Builder builder() {
    return new AutoValue_Person.Builder();
  }

  @AutoValue.Builder
  public abstract static class Builder {

    public abstract Builder name(String name);

    public abstract Person build();
  }
}

当我运行:

Person person = Person.builder().name("Test").build();
StringWriter stringWriter = new StringWriter();
JAXB.marshal(person, stringWriter);
String xmlContent = stringWriter.toString();
System.out.println(xmlContent);

我总是得到:

com.example.commands.AutoValue_Person does not have a no-arg default constructor.
    this problem is related to the following location:
        at com.example.commands.AutoValue_Person
JAXB annotation is placed on a method that is not a JAXB property
    this problem is related to the following location:
        at @javax.xml.bind.annotation.XmlElement(name=##default, namespace=##default, type=class javax.xml.bind.annotation.XmlElement$DEFAULT, required=false, defaultValue=�, nillable=false)
        at com.example.commands.AutoValue_Person

我想让它在不需要创建适配器的情况下工作,如 http://blog.bdoughan.com/2010/12/jaxb-and-immutable-objects.html . I have too many data objects and I don't want to duplicate each one of them. Curious enough, there seems to be tons of utilisations for AutoValue with JAXB in GitHub without the use of adapters: https://github.com/search?q=XmlRootElement+autovalue&type=Code

中所建议

其实是看了你的github link才发现问题的,具体是这个:https://github.com/google/nomulus/blob/8f2a8835d7f09ad28806b2345de8d42ebe781fe6/core/src/main/java/google/registry/model/contact/ContactInfoData.java

注意示例 AutoValue Java class 中使用的命名结构,它仍然使用 getValsetVal

这是一个基于我现在可以运行的代码的简单示例:

import com.google.auto.value.AutoValue;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "Customer")
@XmlType(propOrder = {"name", "age", "id"})
@AutoValue.CopyAnnotations
@AutoValue
public abstract class Customer {

    public static Builder builder() {
        return new AutoValue_Customer.Builder();
    }

    @XmlElement(name = "name")
    abstract String getName();

    @XmlElement(name = "age")
    abstract int getAge();

    @XmlAttribute(name = "id")
    abstract int getId();

    @AutoValue.Builder
    public abstract static class Builder {
        public abstract Builder setName(String name);

        public abstract Builder setAge(int age);

        public abstract Builder setId(int id);

        public abstract Customer build();
    }
}

请注意,我在生成器中使用 setName(String name),但在 class 本身中使用 String getName()。尝试根据这些约定重构您的代码。