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

以上介绍了注解类的定义,但是定义完之后,注解类具体怎么实现,这个后面的文章再说,先干活了,,

 

 

 

 

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