gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:19:32 25 4
gpt4 key购买 nike

给定以下类:

@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 中所建议的那样.我有太多数据对象,我不想复制每一个。奇怪的是,在不使用适配器的情况下,GitHub 中似乎有大量使用 JAXB 的 AutoValue:https://github.com/search?q=XmlRootElement+autovalue&type=Code

最佳答案

在研究了您的 github 链接后,我实际上意识到了这个问题,特别是这个:https://github.com/google/nomulus/blob/8f2a8835d7f09ad28806b2345de8d42ebe781fe6/core/src/main/java/google/registry/model/contact/ContactInfoData.java

注意示例 AutoValue Java 类中使用的命名结构,它仍然使用 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),但在类本身中使用了 String getName()。尝试根据这些约定重构您的代码。

关于java - 将 JAXB 与 AutoValue 结合使用时出现编码错误 "does not have a no-arg default constructor",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59731308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com