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ū)域,有
Method
、Type
、CONSTRUCTOR