一、什么是注解
注解英文为Annotations,官方给出的解释是:
Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.
上面的翻译过来就是:注解是一种元数据的格式,它提供关于程序但又不属于程序自身的数据。注解对它注释的代码没有直接的影响。
二、注解的形式
最简单的注解@Entity
,@符号就是跟编译器表明接下来的是一个注解。常见的注解有@Override
,当然注解也可以包含元素例如:
@Author {
name = "Dave Z"
date = "2017/2/27"
}
class MyClass() {...}
or
@SuppressWarnings(value = "unchecked")
void myMethod() {...}
如果注解中只有一个名为value的元素,那么名字可以被省略,形式为:
@SuppressWarnings("unchecked")
void myMethod() {...}
当然如果一个注解中没有任何的元素,那么括号是可以省略的,比如@Override
。可以看看Override的源码:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
当然同一个声明的地方也是可以使用多个注解的。
@Author(name = "Jane Doe")
@EBook
class MyClass {...}
如果注解有相同的类型,这种情况我们称之为重复注解,例如:
@Author(name = "Jane")
@Author(name = "John")
class MyClass {...}
这种重复的注解只有在Java SE 8 release版本才被支持,具体我们稍后介绍。
三、注解可被用于哪些地方
注解能被用于声明,包括类的声明,字段的声明,方法的声明和其他程序元素的声明。通常我们声明注解的地方都在它自己的那行。随着Java SE 8的发布,注解也能被应用于类型的使用,下面是一些例子:
// 类实例创建的表达
new @Interned MyObject();
// 类型转化
myString = (@NonNull String) str;
// 条款的实现
class UnmodifiableList<T> implements @Readonly List<@Readonly T> {...}
// 抛出异常的声明
void monitorTemperature() throws @Critical TemperatureException {...}
四、声明一个注解类型
代码中很多注解替换了注释,通常传统的软件团体每个类的时候,都会通过注释提供一些重要的信息:
public class Generation3List extends Generation2List {
// Author: John Doe
// Date: 3/17/2002
// Current revision: 6
// Last modified: 4/12/2004
// By: Jane Doe
// Reviewers: Alice, Bill, Cindy
// class code goes here
}
使用注解去添加相同的信息,你必须 先定义注解类型。
@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();
}
注解类型的定义看起来似乎是在关键字interface
前面添加了@
符号。注解类型是接口的一种形式,目前你不用明白接口,后面我们会讲到。
当注解被定以后,我们可以这样使用那么类型的注解:
@ClassPreamble (
author = "John Doe",
date = "3/17/2002",
currentRevision = 6,
lastModified = "4/12/2004",
lastModifiedBy = "Jane Doe",
// Note array notation
reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {
// class code goes here
}
为了使得在@ClassPreamble
出现在Javadoc-generated 文档中,你必须标注@ClassPreamble
使用@Documented
注解。
// import this to use @Documented
import java.lang.annotation.*;
@Documented
@interface ClassPreamble {
// Annotation element definitions
}
五、预定义注解类型
一系列的注解类型被预定义在Java SE API中。一些注解类型被Java编译器使用,一些被应用于其他注解。
被Java语言使用的注解类型
被预定义在java.lang
中的注解类型有@Deprecated, @Override
和@SuppressWarnings
,具体什么意思不在赘述。应用于其他注解的注解
应用于其他注解的注解被称为元注解
。在java.lang.annotation
中定义了几个元注解类型。
@Retention- RetentionPolicy.SOURCE
- RetentionPolicy.CLASS
- RetentionPolicy.RUNTIME
@Documented
>
@Target
@Inherited
@Repeatable