java之注解

93 阅读1分钟

注解的作用

  1. 特殊的注释,可以用代码获取到注解的内容,并根据内容自定义操作
  2. 例如@Override可以在编译的时候检查是否是重写方法
  3. 可以利用反射获取到运行时注解的内容,并自定义操作

元注解

  1. 用来修饰自定义注解的注解

Target

  1. 表示注解可以作用于(修饰)哪些结构
  2. ElementType.PACKAGE 可以修饰包
  3. ElementType.Type 可以修饰类、接口、注解或枚举类型
  4. ElementType.CONSTRUCTOR 可以修饰构造方法
  5. ElementType.FIELD 可以修饰属性(成员变量),包括枚举常量
  6. ElementType.METHOD 可以修饰方法
  7. ElementType.PAPAMETER 可以修饰参数
  8. ElementType.LOCAL_VARIABLE 可以修饰局部变量
  9. ElementType.ANNOTATION_TYPE 可以修饰注解类

Retention

  1. 表示注解的生命周期
  2. RetentionPolicy.SOURCE:  只有编译器能使用,不会保存在class文件中
  3. RetentionPolicy.CLASS: 会保留在 class 文件中,但是运行时无法获取。 这是默认值。
  4. RetentionPolicy.RUNTIME: 编译器、class文件、运行时均可以获取注解内容,通过反射获取该注解。

Repeatable

  1. 表示在同一结构上可以存在多个相同注解

Documented

  1. 表示注解可以被javadoc工具提取并保留

Inherited

  1. 表示该注解会被子类继承

自定义注解

  1. 使用元注解来表示自定义注解的一些重要特性
  2. 可以自定义属性值
package com.annotation;

import java.lang.annotation.*;
import java.lang.reflect.Field;

@AnnotationDemo()
public class AnnotationTest {
    @AnnotationDemo(word = "hi")
    static int name = 1;

    public static void main(String[] args) {
        Class cl = AnnotationTest.class;
        Annotation[] annotations = cl.getDeclaredAnnotations();
        for (Annotation an : annotations) {
            if(an instanceof AnnotationDemo) {
                AnnotationDemo ant = (AnnotationDemo) an;
                System.out.println(ant.word()); // "hello"
            }
        }

        Field[] declaredFields = cl.getDeclaredFields();
        for (Field field : declaredFields) {
            Annotation[] fieldAnnotations = field.getDeclaredAnnotations();
            for (Annotation an : fieldAnnotations) {
                if(an instanceof AnnotationDemo) {
                    AnnotationDemo ant = (AnnotationDemo) an;
                    System.out.println(ant.word()); // "hi"
                }
            }
        }
    }
}

@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface AnnotationDemo {
    String word() default "hello";
}