什么?还不会使用注解Annotation?!基础差的同学赶紧补习吧!😅
- 1.作用
- 2.定义注解
- 3.处理注解
- 4.使用
1.注解的作用
注解(Annotation)是放在Java源码的类、方法、字段、参数前的一种特殊“注释”,并且可以被编译器打包进.class
文件,因此,它是一种用作标注的“元数据”:
// this is a component:
@Resource("hello")
public class Hello {
@Inject
int n;
@PostConstruct
public void hello(@Param String name) { System.out.println(name); }
@Override
public String toString() { return "Hello"; }
}
注解分为三类:
- 第一类 由编译器使用:
@Override
:让编译器检查该方法是否正确地实现了覆写;
@SuppressWarnings
:告诉编译器忽略此处代码产生的警告。
这类注解不会被编译进入.class文件,它们在编译后就被编译器扔掉了。 - 第二类 由工具处理.class文件使用的注解:
比如对class做动态修改,实现一些特殊的功能。这类注解会被编译进入.class文件,但加载结束后并不会存在于内存中。
这类注解只被一些底层库使用,一般我们不必自己处理。 - 第三类:程序运行期能读取的注解:
如上面代码中,配置了@PostConstruct
的方法,调用构造方法后自动被调用(这是Java代码读取该注解实现的功能,JVM并不会识别)。
在加载后一直存在于JVM中,是最常用的注解。
注解可以有参数,必须是常量(具体的值),包括:
- 所有基本类型;
- String;
- 枚举类型;
- 基本类型、String以及枚举的数组。
注解的参数可以有默认值,缺少某个参数时将使用默认值。
此外,大部分注解会有一个名为value的配置参数,对此参数赋值,可以只写常量,相当于省略了value参数。
如果只写注解,相当于全部使用默认值:
public class Hello {
@Check(min=0, max=100, value=55)
public int n;
@Check(value=99)
public int p;
@Check(99) // @Check(value=99)
public int x;
@Check // 表示所有参数都使用默认值!
public int y;
}
2.定义注解
Java语言使用 @interface
语法来定义注解,它的格式如下:
public @interface Report {
// 像是无参数的方法,可以用default设定一个默认值(强烈推荐)
// 最常用的参数应当命名为value
int type() default 0;
String level() default "info";
String value() default "";
}
元注解:@Target,@Retention,@Repeatable,@Inherited
可以修饰其他注解的注解称为——元注解(meta annotation)。Java标准库已经定义了一些元注解,我们只需要使用,不需要自己去编写元注解。
@Target
最常用的元注解是@Target
。使用@Target
可以定义Annotation
能够被应用于源码的哪些位置:
- 类或接口:
ElementType.TYPE
- 字段:
ElementType.FIELD
- 方法:
ElementType.METHOD
- 构造方法:
ElementType.CONSTRUCTOR
- 方法参数:
ElementType.PARAMETER
例如,定义注解@Report可用在方法上,我们必须添加一个@Target(ElementType.METHOD)
:
@Target(ElementType.METHOD)
public @interface Report {
String value() default "";
}
// 可用在方法或字段上:
@Target({
ElementType.METHOD,
ElementType.FIELD
})
public @interface Report {
String value() default "";
}
@Retention
另一个重要的元注解@Retention
定义了Annotation
的生命周期:
- 仅编译期:
RetentionPolicy.SOURCE
- 仅class文件:
RetentionPolicy.CLASS
- 运行期:
RetentionPolicy.RUNTIME
如果@Retention
不存在,则该Annotation
默认为CLASS
。因为通常我们自定义的Annotation
都是RUNTIME
,所以,务必要加上这个元注解:
@Retention(RetentionPolicy.RUNTIME)
public @interface Report {
String value() default "";
}
@Repeatable
使用@Repeatable
这个元注解可以定义Annotation
是否可重复。这个注解应用不是特别广泛。
@Repeatable
@Target(ElementType.TYPE)
public @interface Report {
String value() default "";
}
经过@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
的继承无效:
@Inherited
@Target(ElementType.TYPE)
public @interface Report {
String value() default "";
}
// 在使用的时候,如果一个类用到了@Report:
@Report(type=1)
public class Person {
}
// 则它的子类默认也定义了该注解:
public class Student extends Person {
}
必须设置
@Target
和@Retention
,@Retention
一般设置为RUNTIME
,因为我们自定义的注解通常要求在运行期读取。一般情况下,不必写@Inherited
和@Repeatable
3.处理注解
我们只需要学习读取
@Retention(RetentionPolicy.RUNTIME)
类型的注解。
所有的注解都继承自java.lang.annotation.Annotation,因此,读取注解,需要使用反射API。
Java提供的使用反射API读取Annotation的方法包括:
判断某个注解是否存在于Class、Field、Method或Constructor:
Class.isAnnotationPresent(Class)
Field.isAnnotationPresent(Class)
Method.isAnnotationPresent(Class)
Constructor.isAnnotationPresent(Class)
例如,判断@Report是否存在于Person类::
// 判断@Report是否存在于Person类:
Person.class.isAnnotationPresent(Report.class);
使用反射API读取Annotation:
Class.getAnnotation(Class)
Field.getAnnotation(Class)
Method.getAnnotation(Class)
Constructor.getAnnotation(Class)
例如,获取Person定义的@Report注解:
// 获取Person定义的@Report注解:
Report report = Person.class.getAnnotation(Report.class);
int type = report.type();
String level = report.level();
使用反射API读取Annotation
有两种方法。方法一是先判断Annotation
是否存在,如果存在,就直接读取:
Class cls = Person.class;
if (cls.isAnnotationPresent(Report.class)) {
Report report = cls.getAnnotation(Report.class);
...
}
第二种方法是直接读取Annotation
,如果Annotation
不存在,将返回null:
Class cls = Person.class;
Report report = cls.getAnnotation(Report.class);
if (report != null) {
...
}
读取方法、字段和构造方法的Annotation
和Class
类似。但要读取方法参数的Annotation
就比较麻烦一点,因为方法参数本身可以看成一个数组,而每个参数又可以定义多个注解,所以,一次获取方法参数的所有注解就必须用一个二维数组来表示。例如,对于以下方法定义的注解:
public void hello(@NotNull @Range(max=5) String name,
@NotNull String prefix) {
}
要读取方法参数的注解,我们先用反射获取Method实例,然后读取方法参数的所有注解:
// 获取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;
}
}
4.使用注解
如何使用,完全由程序自己决定。例如,JUnit是一个测试框架,它会自动运行所有标记为@Test
的方法。
我们来看一个@Range
注解,我们希望用它来定义一个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不会自动给注解添加任何额外的逻辑。
注解真的很有用,关于更多的使用场景,要在实际工作中多多思考
其他语法使用:Java基本功系列之☞泛型
(End)