Annotation 注解 探究(一)

来源:互联网 发布:网架设计软件 编辑:程序博客网 时间:2024/04/30 14:00

首先我们先明确目标什么是Annotation ,我们能用它来干什么?

 

第一步,我们来看下JAVA对Annotation 的定义:


public interface Annotation

The common interface extended by all annotation types. Note that an interface that manually extends this one does not define an annotation type. Also note that this interface does not itself define an annotation type.

 

从上面的描述中我们可以看出Annotation其实是一个接口,但是注意,我们不能手动的去继承这个接口来定义一个Annotation类型,而且这个接口本身也不能定义一个Annotation 类型。

 

第二步,我们来看一个名为Target 的Annotation 类型的实现:

 

从上面的代码我们可以看出他有一个方法,返回值是ElementType[],接口我们来看下ElementType 是个什么东东:

哦,原来它只是一个枚举类型而已。那么这有什么用呢,我们还是来看下官方的文档:

 

 

Target

Indicates the kinds of program element to which an annotation type is applicable. If a Target meta-annotation is not present on an annotation type declaration, the declared type may be used on any program element. If such a meta-annotation is present, the compiler will enforce the specified usage restriction.

 

从这个文档中我们可以看出要声明一个Annotation 类型,我们要使用如下的语句

 

,如果我们有一个自定义的Annotation 类型中没有Target 的声明,那么我们定义的这个Annotation 类型可以用于程序中的任何元素上,比如变量、方法、类 等。如果我们使用Target,那么编译器会强制要求符合这个规则。

 

比如:我们定义了一个Annotation 类型有如下声明:

 

表明这个Annotation 只能用在变量上,而不能用在其他元素上,如象以下使用就会出错:

 

第三步,除了以上所说的,还有其他什么Annotation 么?

回答是有,java 提供了四种类型的meta-data:

  • Target
  • Documented
  • Inherited
  • Retention

Documented 表明一个类型的Annotation将会被JAVADOC或其他类型工具记录。也就是说有了这个Annotation 后就会把用这个注释的类型放入API 文档中。

 

Inherited 表明使用这个Annotation 的类型会自动继承。也就是说,这个Annotation 规范了Annotation上的查找规则,如果使用的Annotation 找不到方法,就会自动查找父类的Annotation ,并且这个Annotation 只能用于Annotation的类型。

 

Retention 表明这个Annotation 能维持多久。

 

以上所述的四种Annotation 是基本的信息Annotation,他们只能用于Annotation,可以从源代码看出,他们的Target 都是

 

总结下:

在这章中主要叙述了什么是Annotation 以及一些内置的Annotation的说明,关于如何使用将在下章解释