3类注解
1、由编译器使用的注解,这类注解不会被编译进入.class
文件,它们在编译后就被编译器扔掉了。如@Override
、@SuppressWarnings
。
2、由工具处理.class
文件使用的注解,比如有些工具会在加载class的时候,对class做动态修改,实现一些特殊的功能。这类注解会被编译进入.class
文件,但加载结束后并不会存在于内存中。这类注解只被一些底层库使用,一般我们不必自己处理。
3、在程序运行期能够读取的注解,它们在加载后一直存在于JVM中,这也是最常用的注解。例如,一个配置了@PostConstruct
的方法会在调用构造方法后自动被调用(这是Java代码读取该注解实现的功能,JVM并不会识别该注解)。
注解的配置参数
(1)定义一个注解时,还可以定义配置参数。
(2)配置参数必须是常量。
(3)没有指定配置的参数使用默认值。
(4)如果参数名称是value
,且只有一个参数,那么可以省略参数名称。
元注解
(1)有一些注解可以修饰其他注解,这些注解就称为元注解(meta annotation)。
(2)怎样变成元注解(使用@Target(ElementType.ANNOTATION_TYPE)
)。
@Target
定义注解能够被应用于源码的哪些位置。
- 类、接口(包括注解类型)或枚举:
ElementType.TYPE
- 字段:
ElementType.FIELD
- 方法:
ElementType.METHOD
- 参数:
ElementType.PARAMETER
- 构造方法:
ElementType.CONSTRUCTOR
- 局部变量:
ElementType.LOCAL_VARIABLE
- 注解类型:
ElementType.INNOTATION_TYPE
- 包:
ElementType.PACKAGE
- 类型参数:
ElementType.TYPE_PARAMETER
- ALL(默认):
ElementType.TYPE_USE
//定义注解
@Target({ElementType.TYPE, ElementType.FIELD})
@interface Report {
}
//使用注解
@Report
class Person {
@Report
private String name;
}
@Retention
标识这个注解怎么保存,是只在代码中,还是编入class文件中,或者是在运行时可以通过反射访问。
- 仅编译期:
RetentionPolicy.SOURCE
; - 仅class文件(默认):
RetentionPolicy.CLASS
; - 运行期:
RetentionPolicy.RUNTIME
。
@Repeatable
Java 8 开始支持,标识某注解可以在同一个声明上使用多次。这个注解应用不是特别广泛。
@Repeatable(Reports.class)
@Target(ElementType.TYPE)
public @interface Report {
int type() default 0;
String level() default "info";
String value() default "";
}
@Target(ElementType.TYPE)
public @interface Reports {
Report[] value();
}
经过@Repeatable
修饰后,在某个类型声明处,就可以添加多个@Report
注解:
//Hello 有注解 Reports,没有注解 Report
//如果只有一个 Report,则有注解 Report,没有注解 Reports
@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 {
int type() default 0;
String level() default "info";
String value() default "";
}
在使用的时候,如果一个类用到了@Report
:
@Report(type=1)
public class Person {
}
则它的子类默认也定义了该注解:
public class Student extends Person {
}
@Documented
标记这些注解是否包含在用户文档中。
自定义注解
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Report {
int type() default 0;
String level() default "info";
String value() default "";
}
处理注解
判断拥有注解
判断某个注解是否存在于Class
、Field
、Method
或Constructor
:
Class.isAnnotationPresent(Class)
Field.isAnnotationPresent(Class)
Method.isAnnotationPresent(Class)
Constructor.isAnnotationPresent(Class)
例如:
// 判断@Report是否存在于Person类:
Person.class.isAnnotationPresent(Report.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();
使用反射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;
}
}
获取注解方法归纳
首先,了解一下被@Repeatable
注解的注解,如下:
@Repeatable(Reports.class)
@Retention(RetentionPolicy.RUNTIME)
@interface Report {
int type();
}
@Retention(RetentionPolicy.RUNTIME)
@interface Reports {
Report[] value();
}
如果某个地方只注解了1次@Report
,则该地方只有@Report
注解。
如果某个地方注解了2次@Report
,则该地方只有@Reports
注解。
第1类,搜索范围:自己+父类
Annotation[] annotations = cls.getAnnotations();//获取所有注解
Report annotation = cls.getAnnotation(Report.class);//获取单个指定注解
Report[] annotationsByType = cls.getAnnotationsByType(Report.class);//获取多个指定注解。但是对于@Repeatable注解的注解,会尽力寻找
第2类,搜索范围:自己
//同第1类,只是搜索范围不同
Annotation[] declaredAnnotations = cls.getDeclaredAnnotations();
Report declaredAnnotation = cls.getDeclaredAnnotation(Report.class);
Report[] declaredAnnotationsByType = cls.getDeclaredAnnotationsByType(Report.class);
例子:检查字段大小范围
我们来看一个@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());
}
}
}
}
}
例子:简易版JUnit
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Person p = new Person();
test(p);
}
static void test(Object obj) {
Method[] methods = obj.getClass().getMethods();
List<Method> testMethods = Arrays.stream(methods)
.filter(method -> method.isAnnotationPresent(Test.class))
.collect(Collectors.toList());
List<Method> beforeMethods = Arrays.stream(methods)
.filter(method -> method.isAnnotationPresent(Before.class))
.collect(Collectors.toList());
try {
for (Method testMethod : testMethods) {
// 打印方法信息
{
String className = obj.getClass().getCanonicalName();
String methodName = testMethod.getName();
String msg = String.format("---【%s#%s】---", className, methodName);
System.out.println(msg);
}
// Before
for (Method beforeMethod : beforeMethods) {
beforeMethod.invoke(obj);
}
// Test
testMethod.invoke(obj);
}
} catch (Throwable e) {
System.out.println("find throwable:\n" + e);
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Before {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Test {
}
class Person {
@Test
public void test_say() {
System.out.println("test say()");
}
@Test
public void test_run() {
System.out.println("test run()");
}
@Before
public void setup() {
System.out.println("do setup");
}
}