问题
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:
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.
回答1:
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?
回答2:
There are a couple of different options:
Option #1 - Introduce a Field
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:
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
If the value is calculated then you will need to introduce a JavaBean accessor and have JAXB map to that:
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();
}
}
来源:https://stackoverflow.com/questions/7994479/is-it-possible-to-xmlelement-annotate-a-method-with-non-stardard-name