Annotation

Use

  • 給compiler提供信息,用來檢測錯誤,如@override
  • 在編譯期,一些工具(如apt)可以通過Annotation信息來生成一些代碼
  • 在運行期間,可以用來檢測,如@NonNull

Declaring an Annotation Type

For Example:

先定義Annotation:

@interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

使用:

@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)

Predefined Annotation Types

Annotation Types Used by the Java Language

下面三個Annotation在java.lang中被定義

  • @Deprecated 標(biāo)記的元素是不推薦使用的,使用會產(chǎn)生warning。如果聲明了@Deprecated,應(yīng)該給出棄用的理由以及用什么替代
  • @SuppressWarnings 不產(chǎn)生warning
  • @Override

Annotations That Apply to Other Annotations

下面的Annotations在java.lang.annotation被定義,用來“修飾”其他Annotation。

  • @Rentation 指示被其修飾的Annotation如何被存儲:
    • Source:被compiler忽略,只保留在Java Source Code這個層面
    • Class:在編譯期被保留,被JVM忽略
    • Runtime:在運行期被保留
  • @Target 表明被其修飾的Annotation作用的區(qū)域,有MethodTypeCONSTRUCTOR
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容