簡體   English   中英

Java注解:元素聲明為方法,但值設置為屬性

[英]Java annotation: elements declared as method but value set as attribute

創建自定義批注時,我們將元素聲明為方法,然后將值設置為屬性。

例如,在這里我們聲明了一個自定義注釋ComponentType ,其元素name()description()看起來像方法。

public @interface ComponentType {
    String name();// declared as method
    String description();
}

使用注釋時,它們如下所示:

@ComponentType(name = "userContainer", // value looks like an attribute
               description = "a user container")
public class UserEntity { }

我的問題是 :Java為什么不允許這樣將元素聲明為屬性?

public @interface ComponentType {
    String name; // Compilation Error
    String description;
}

如果注釋的屬性未在接口中定義為抽象方法,則它們將成為成員。 就像是:

public @interface ComponentType {
    String name;
    String description;
}

但是,接口中的所有成員都是隱式的final (和static ),並且上面的代碼無法編譯,因為namedescription未初始化。

但是,如果它們實際上是使用一些值初始化的:

public @interface ComponentType {
    String name = "name";
    String description = "description";
}

則不可能出現以下片段:

@ComponentType(
  name = "userContainer" //cannot assign a value to a final variable 
, description = "a user container")

我的觀察是:

Java將注釋視為接口的特殊類型,因此:

  1. 像接口一樣,我們只能在注釋中聲明最終屬性:

     String appName = "test application";//final attribute, never reset value 
  2. 注釋只能包含抽象方法(聲明的方法無需實現)。

     public @interface ComponentType { String name();// declared as abstract method 
  3. 當我們通過注釋對元素(例如類,方法,屬性)進行注釋時,我們需要設置這些抽象方法的返回值,這些返回方法看起來像屬性,但實際上是一種實現。

     @ComponentType(name = "userContainer"//set return value of method name() 
  4. 我們可以通過簡單地調用批注的抽象方法來使用在批注元素(例如,類,方法,屬性)中設置的值。

     Annotation annotation = annotatedClassObject.getAnnotation(ComponentType.class); ComponentType componentType = (ComponentType) annotation; String someName = componentType.name(); //returns value set during annotating 

就像界面一樣

  • 注釋永遠不支持聲明任何非最終屬性。
  • 注釋可能包含一些抽象方法 ,我們需要在被注釋的元素(例如類,方法,屬性)期間設置抽象方法的返回值。

期待更多反饋/答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM