1、Annotation

java.lang包有很多類及子包,因爲java.lang.annotation中的類少,簡單,所以就先看了下這個包。

看源碼有兩大工具:API 和JLS,另外看源碼一定要看註釋,這一點非常非常重要。

API:https://docs.oracle.com/javase/8/docs/api/

JLS:https://docs.oracle.com/javase/specs/

我用的是jdk1.8的兩個文檔。

Annotation的第一行註釋就是The common interface extended by all annotation types,所有註釋類型擴展的公共接口。

那麼什麼是annotation type?

在JLS 9.6中,描述了這個定義。annotation type其實是一種接口類型,只不過爲了區分與普通接口的不同,所以使用了@+interface的方式來表示。

原文註釋是這樣的:

An annotation type declaration specifies a new annotation type, a special kind
of interface type. To distinguish an annotation type declaration from a normal
interface declaration, the keyword interface is preceded by an at-sign (@).

 

我們平常的寫法都是@interface,其實@和interface是兩個關鍵詞,可以用逗號隔開使用,java開發規範中也講了這一點,只不過因爲風格問題,所以一般要求都是連起來寫。

原文註釋:

Note that the at-sign (@) and the keyword interface are distinct tokens. It is possible to
separate them with whitespace, but this is discouraged as a matter of style.
 
 
在annotation中,定義了一些meta-annotation元註解。最常用的就是

我們自定義註解使用到的元註解也基本是這三個。

@Documented :

如果用Documented註釋類型聲明,則其註釋將成爲已註釋元素的公共API的一部分。在我們自定義註解的時候,其實這個註解用不用,並不會影響我們正常的功能,起碼我測試的時候是沒有問題的。

@Retention

用來指定註釋的保留策略。具體的值是由RetentionPolicy的Enum定義的,總共有三種策略:

CLASS

Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.(默認值)

RUNTIME

Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

SOURCE

Annotations are to be discarded by the compiler.

@Target

用來指定當前註解類可以用在哪些對象上面,具體的值是由ElementType的Enum定義的,

ANNOTATION_TYPE

Annotation type declaration

CONSTRUCTOR

Constructor declaration

FIELD

Field declaration (includes enum constants)

LOCAL_VARIABLE

Local variable declaration

METHOD

Method declaration

PACKAGE

Package declaration

PARAMETER

Formal parameter declaration

TYPE

Class, interface (including annotation type), or enum declaration

TYPE_PARAMETER

Type parameter declaration

TYPE_USE

Use of a type

以上介紹了註解類的定義,但是定義完之後,註解類具體怎麼實現,這個後面的文章再說,先幹活了,,

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章