2014-10-07 113 views
1

我最近在一個s​​etter上使用的項目中看到了這個JAXB註釋。我從我自己的經驗中知道@XmlElement可以用於屬性和getter。我不確定這個註釋是否可以並且應該用在setter上,我搜索了它並且找不到明確的答案。請指教。哪裏可以放置@XmlElement?

回答

2

從JAXB 2.2規範的章節「8.9屬性&字段」(參見:https://jcp.org/aboutJava/communityprocess/mrel/jsr222/index2.html

對於屬性,一個給定的註釋可以應用於讀取或 寫屬性而不是兩者。

換句話說,註釋可以放在get或set方法中。根據我的經驗,大多數人把註釋放在get方法上。

2

The code明確表示它的制定者的工作:

public abstract class AbstractInlineAnnotationReaderImpl<T,C,F,M> 
    implements AnnotationReader<T,C,F,M> { 
... 

    public final <A extends Annotation> A getMethodAnnotation(Class<A> annotation, M getter, M setter, Locatable srcPos) { 
     A a1 = getter==null?null:getMethodAnnotation(annotation,getter,srcPos); 
     A a2 = setter==null?null:getMethodAnnotation(annotation,setter,srcPos); 

     if(a1==null) { 
      if(a2==null) 
       return null; 
      else 
       return a2; 
     } else { 
      if(a2==null) 
       return a1; 
      else { 
       // both are present 
       getErrorHandler().error(new IllegalAnnotationException(
        Messages.DUPLICATE_ANNOTATIONS.format(
         annotation.getName(), fullName(getter),fullName(setter)), 
        a1, a2)); 
       // recover by ignoring one of them 
       return a1; 
      } 
     } 
    } 
... 
} 

不過,我也無法找到這個規範性引用。

+1

我已經添加了一個答案與規範參考:http://stackoverflow.com/a/26259767/383861 – 2014-10-08 14:44:52

相關問題