Search code examples
javajaxbjaxb2

Is it possible to @XmlElement annotate a method with non-stardard name?


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.


Solution

  • 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?