【问题标题】:Is it possible to @XmlElement annotate a method with non-stardard name?是否可以 @XmlElement 用非标准名称注释方法?
【发布时间】:2011-12-21 02:57:31
【问题描述】:

这就是我正在做的:

@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

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

【问题讨论】:

    标签: java jaxb jaxb2


    【解决方案1】:

    有几个不同的选项:

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

    【讨论】:

    • 那我为什么还需要title()
    • @yegor256 - JAXB 不需要 title() 方法。
    • 但我需要它:) 我需要title() 来返回值。 Thor84no 提出的解决方案是目前最好的,但我真的希望它不是唯一的。同样,title() 必须返回值
    • @yegor256 - 如我的代码示例所示,您绝对可以拥有title() 方法,它只是不被JAXB 实现使用。 title() 方法返回的值是常量还是计算出来的?
    • 由于该值是计算出来的,因此您需要引入 Thor84no 给出的 get 方法。但是,我不会像该答案中指定的那样介绍该字段。我已经更新了答案的外观。
    【解决方案2】:

    可能有更好的方法,但想到的第一个解决方案是:

    @XmlElement(name = "title")
    private String title;
    
    public String getTitle() {
        return title();
    }
    

    为什么你不能按照 Java 约定来命名你的方法?

    【讨论】:

    • 这里的变量是多余的,@XmlElement-annotated getTitle() 就足够了
    • 我不确定,所以我把它放在以防万一,因为它肯定会起作用。
    • +1 - 注释具有相应访问器的字段(实例变量)时,您需要确保设置 @XmlAccessorType(XmlAccessType.FIELD):blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html。同样在这种情况下,JAXB 将为 title 属性应用默认映射,因此不需要 @XmlElement 注释。
    猜你喜欢
    • 1970-01-01
    • 2013-11-18
    • 2016-02-15
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 2015-10-01
    相关资源
    最近更新 更多