gpt4 book ai didi

java - @XmlElement 是否可以使用非标准名称注释方法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:07:16 28 4
gpt4 key购买 nike

这就是我正在做的:

@XmlType(name = "foo")
@XmlAccessorType(XmlAccessType.NONE)
public final class Foo {
@XmlElement(name = "title")
public String title() {
return "hello, world!";
}
}

JAXB 提示:

com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
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(nillable=false, name=title, required=false, defaultValue=, type=class javax.xml.bind.annotation.XmlElement$DEFAULT, namespace=##default)
at com.example.Foo

要做什么?我不想(也不能)重命名该方法。

最佳答案

有几个不同的选项:

选项 #1 - 引入字段

如果该值像您的示例中那样是常量,那么您可以将一个字段引入您的领域类,并让 JAXB 映射到该字段:

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "foo")
@XmlAccessorType(XmlAccessType.NONE)
public final class Foo {
@XmlElement
private final String title = "hello, world!";

public String title() {
return title;
}
}

选项 #2 - 引入属性

如果计算值,则需要引入 JavaBean 访问器并将 JAXB 映射到该访问器:

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "foo")
@XmlAccessorType(XmlAccessType.NONE)
public final class Foo {

public String title() {
return "hello, world!";
}

@XmlElement
public String getTitle() {
return title();
}

}

关于java - @XmlElement 是否可以使用非标准名称注释方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7994479/

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