@XmlElement是否可以使用非标准名称注释方法?

时间:2011-11-03 12:00:50

标签: java jaxb jaxb2

这就是我正在做的事情:

@XmlType(name = "foo")
@XmlAccessorType(XmlAccessType.NONE)
public final class Foo {
  @XmlElement(name = "title")
  public String title() {
    return "hello, world!";
  }
}

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

怎么办?我不希望(也不能)重命名该方法。

2 个答案:

答案 0 :(得分:5)

有几种不同的选择:

选项#1 - 介绍字段

如果值在示例中是常量,那么您可以在域类中引入一个字段并让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;
  }
}

选项#2 - 介绍属性

如果计算了该值,那么您需要引入一个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();
  }

}

答案 1 :(得分:3)

可能有更好的方法,但首先想到的解决方案是:

@XmlElement(name = "title")
private String title;

public String getTitle() {
    return title();
}

为什么你不能根据Java惯例命名你的方法?