什么是注解(Annotation)?注解是放在Java源码的类、方法、字段、参数前的一种特殊“注释”
注释会被编译器直接忽略,注解则可以被编译器打包进入class文件,因此,注解是一种用作标注的“元数据”。
注解的作用
三类注解
- 由编译器使用的注解,不会被编译进入
.class
文件,它们在编译后就被编译器扔掉了:
@Override
:让编译器检查该方法是否正确地实现了覆写;@SuppressWarnings
:告诉编译器忽略此处代码产生的警告。
- 由工具处理
.class
文件使用的注解,比如有些工具会在加载class的时候,对class做动态修改,实现一些特殊的功能。这类注解会被编译进入.class
文件,但加载结束后并不会存在于内存中。这类注解只被一些底层库使用,一般我们不必自己处理 - 在程序运行期能够读取的注解,它们在加载后一直存在于JVM中,这也是最常用的注解。
小结:
注解(Annotation)是Java语言用于工具处理的标注:
注解可以配置参数,没有指定配置的参数使用默认值;
如果参数名称是value
,且只有一个参数,那么可以省略参数名称。
定义注解
Java语言使用@interface
语法来定义注解(Annotation
)
public @interface Report {
int type() default 0;
String level() default "info";
String value() default "";
}
注解的参数类似无参数方法,可以用default
设定一个默认值(强烈推荐)。最常用的参数应当命名为value
。
元注解
可以修饰其他注解
@Target | 使用@Target 可以定义Annotation 能够被应用于源码的哪些位置 |
---|---|
类或接口:ElementType.TYPE | |
字段:ElementType.FIELD | |
方法:ElementType.METHOD | |
构造方法:ElementType.CONSTRUCTOR | |
方法参数:ElementType.PARAMETER | |
例如:@Report用在方法上
@Target(ElementType.METHOD)
/*用在方法或字段上
@Target({
ElementType.METHOD,
ElementType.FIELD
})
*/
public @interface Report {
int type() default 0;
String level() default "info";
String value() default "";
}
@Retention | @Retention 定义了Annotation 的生命周期 |
---|---|
仅编译期:RetentionPolicy.SOURCE | |
仅class文件:RetentionPolicy.CLASS | |
运行期:RetentionPolicy.RUNTIME | |
@Retention不存在,则该 Annotation默认为 CLASS |
@Repeatable | 使用@Repeatable 这个元注解可以定义Annotation 是否可重复 |
---|---|
经过@Repeatable 修饰后,在某个类型声明处,就可以添加多个@Report 注解: |
@Report(type=1, level="debug")
@Report(type=2, level="warning")
public class Hello {
}
@Inherited | 使用@Inherited 定义子类是否可继承父类定义的Annotation 。 |
---|---|
@Inherited 仅针对@Target(ElementType.TYPE) 类型的annotation 有效,并且仅针对class 的继承,对interface 的继承无效 | |
如何定义Annotation
第一步,用@interface
定义注解:
public @interface Report {
}
第二步,添加参数、默认值:
public @interface Report {
int type() default 0;
String level() default "info";
String value() default "";
}
把最常用的参数定义为value()
,推荐所有参数都尽量设置默认值。
第三步,用元注解配置注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Report {
int type() default 0;
String level() default "info";
String value() default "";
}
处理注解
因为注解定义后也是一种class
,所有的注解都继承自java.lang.annotation.Annotation
,因此,读取注解,需要使用反射API。
判断某个注解是否存在于Class
、Field
、Method
或Constructor
:
Class.isAnnotationPresent(Class)
Field.isAnnotationPresent(Class)
Method.isAnnotationPresent(Class)
Constructor.isAnnotationPresent(Class)
使用反射API读取Annotation:
Class.getAnnotation(Class)
Field.getAnnotation(Class)
Method.getAnnotation(Class)
Constructor.getAnnotation(Class)
// 获取Person定义的@Report注解:
Report report = Person.class.getAnnotation(Report.class);
int type = report.type();
String level = report.level();
读取方法参数的注解:
public void hello(@NotNull @Range(max=5) String name, @NotNull String prefix) {
}
// 获取Method实例:
Method m = ...
// 获取所有参数的Annotation:
Annotation[][] annos = m.getParameterAnnotations();
// 第一个参数(索引为0)的所有Annotation:
Annotation[] annosOfName = annos[0];
for (Annotation anno : annosOfName) {
if (anno instanceof Range) { // @Range注解
Range r = (Range) anno;
}
if (anno instanceof NotNull) { // @NotNull注解
NotNull n = (NotNull) anno;
}
}
使用注解
例子:
我们希望用它来定义一个String
字段的规则:字段长度满足@Range
的参数定义
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Range {
int min() default 0;
int max() default 255;
}
在某个JavaBean中,我们可以使用该注解
public class Person {
@Range(min=1, max=20)
public String name;
@Range(max=10)
public String city;
}
我们编写一个Person
实例的检查方法,它可以检查Person
实例的String
字段长度是否满足@Range
的定义:
void check(Person person) throws IllegalArgumentException, ReflectiveOperationException {
// 遍历所有Field:
for (Field field : person.getClass().getFields()) {
// 获取Field定义的@Range:
Range range = field.getAnnotation(Range.class);
// 如果@Range存在:
if (range != null) {
// 获取Field的值:
Object value = field.get(person);
// 如果值是String:
if (value instanceof String) {
String s = (String) value;
// 判断值是否满足@Range的min/max:
if (s.length() < range.min() || s.length() > range.max()) {
throw new IllegalArgumentException("Invalid field: " + field.getName());
}
}
}
}
}
通过@Range
注解,配合check()
方法,就可以完成Person
实例的检查。注意检查逻辑完全是我们自己编写的,JVM不会自动给注解添加任何额外的逻辑。