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

早过忘川 提交于 2019-12-12 10:55:51

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!