1. 简单介绍
- 作用:不是程序本身,是作为类似注释的方式对程序作出解释,也存在检查和约束作用
- 格式:使用**@注解名(参数)**格式
- 使用地点:可以在包、类、字段和方法上使用
2. 元注解
用来解释注解的注解,Java中定义了4个标准的元注解 - @Target 描述注解使用范围
- @Retention 表示需要在什么级别保存该注解信息,描述生命周期
- @Document 说明将该注解包含在javadoc中
- @Inherited 说明子类可以继承父类中的该注解
3. 自定义注解
// METHOD:可以定义在方法上, TYPE:可以定义在类上
@Target(value = {ElementType.METHOD, ElementType.TYPE})
// RUNTIME:运行时级别,这里没有指定value = 是因为参数名为value并只有一个参数时可忽略
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
// 该参数指定了默认值为hello,表名不指定该参数时默认为hello
String value() default "hello";
// 该参数为必填项,并且可以使用{"a", "b"}的方式传入多个参数
String[] message();
}
// 该注解声明只作用在字段上
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldAnnotation{
String value();
}
4. 使用注解
@MyAnnotation(message = {"hello", "world"})
class AnnotationDemo {
@FieldAnnotation("String name annotation")
private String name;
@FieldAnnotation("int age annotation")
private int age;
// ... 省略构造器和get/set
}
5. 测试
public static void main(String[] args) throws ClassNotFoundException {
Class<?> clazz = Class.forName("com.demo.AnnotationDemo");
// 获取该类上所有的注解类型
Annotation[] annotations = clazz.getAnnotations();
// 遍历类上注解
for (Annotation annotation : annotations) {
Class<? extends Annotation> annotationType = annotation.annotationType();
// 判断类上注解类型
Annotation annotation1 = clazz.getAnnotation(annotationType);
if (annotation1 instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation1;
// 获取注解信息
String[] message = myAnnotation.message();
String value = myAnnotation.value();
}
}
// 获取该类所有字段
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
FieldAnnotation annotation = field.getAnnotation(FieldAnnotation.class);
// 获取字段上注解的值
String value = annotation.value();
}
// 获取方法上的注解类似
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
//method.getAnnotation()
}
}