java 是否可以@XmlElement 注释具有非标准名称的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7994479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to @XmlElement annotate a method with non-stardard name?
提问by yegor256
This is what I'm doing:
这就是我正在做的:
@XmlType(name = "foo")
@XmlAccessorType(XmlAccessType.NONE)
public final class Foo {
@XmlElement(name = "title")
public String title() {
return "hello, world!";
}
}
JAXB complains:
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
What to do? I don't want (and can't) rename the method.
该怎么办?我不想(也不能)重命名该方法。
采纳答案by Thor84no
There might be a better way, but the first solution that comes to mind is:
可能有更好的方法,但想到的第一个解决方案是:
@XmlElement(name = "title")
private String title;
public String getTitle() {
return title();
}
Why is it you can't name your method according to Java conventions anyway?
为什么无论如何都不能根据 Java 约定来命名方法?
回答by bdoughan
There are a couple of different options:
有几个不同的选项:
Option #1 - Introduce a Field
选项 #1 - 引入一个字段
If the value is constant as it is in your example, then you could introduce a field into your domain class and have JAXB map to that:
如果该值在您的示例中是常量,那么您可以在域类中引入一个字段并将 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;
}
}
Option #2 - Introduce a Property
选项#2 - 介绍房产
If the value is calculated then you will need to introduce a JavaBean accessor and have JAXB map to that:
如果计算了该值,那么您将需要引入一个 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();
}
}