Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jaxb

jaxb2

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.

like image 326
yegor256 Avatar asked Nov 03 '11 12:11

yegor256


1 Answers

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();
  }

}
like image 63
bdoughan Avatar answered Sep 18 '22 11:09

bdoughan