1. 简单介绍
- 作用:不是程序本身,是作为类似注释的方式对程序作出解释,也存在检查和约束作用
- 格式:使用**@注解名(参数)**格式
- 使用地点:可以在包、类、字段和方法上使用
2. 元注解
用来解释注解的注解,Java中定义了4个标准的元注解
-
@Target 描述注解使用范围
-
@Retention 表示需要在什么级别保存该注解信息,描述生命周期
-
@Document 说明将该注解包含在javadoc中
-
@Inherited 说明子类可以继承父类中的该注解
3. 自定义注解
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value() default "hello";
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;
}
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) {
}
}