反射】获取标注内容。在编译标注可以被嵌入到字节码中。Java 虚拟机可以保留注解内容,在运行时可以获取到注解内容 。 也支持自定义 Java 注解。 注解常见的作用有以下几种:1.生成文档。这是最常见的,也是java 最早提供的注解,常用的有@document@param等;2.跟踪代码依赖性,实现替代配置文件功能。比较常见的是spring 2.5 开始的基于注解配置,作用就是减少配置,现在的框架基本都使用了这种配置来减少配置文件的数量;3.在编译时进行格式检查。如@Override放在方法前,如果你这个方法并不是覆盖了超类方法,则编译时就能检查出。

参数说明

java Annotation 的组成中,有 3 个非常重要的主干类。它们分别是:

Annotation.java

package java.lang.annotation;
public interface Annotation {

    boolean equals(Object obj);

    int hashCode();

    String toString();

    Class<? extends Annotation> annotationType();
}

ElementType.java

package java.lang.annotation;

public enum ElementType {
    TYPE,               /* 类、接口(包括注释类型)或枚举声明  */

    FIELD,              /* 字段声明(包括枚举常量)  */

    METHOD,             /* 方法声明  */

    PARAMETER,          /* 参数声明  */

    CONSTRUCTOR,        /* 构造方法声明  */

    LOCAL_VARIABLE,     /* 局部变量声明  */

    ANNOTATION_TYPE,    /* 注释类型声明  */

    PACKAGE             /* 包声明  */
}

RetentionPolicy.java

package java.lang.annotation;
public enum RetentionPolicy {
    SOURCE,            /* Annotation信息仅存在于编译器处理期间,编译器处理完之后就没有该Annotation信息了  */

    CLASS,             /* 编译器将Annotation存储于类对应的.class文件中。默认行为  */

    RUNTIME            /* 编译器将Annotation存储于class文件中,并且可由JVM读入 */
}

实现代码

自定义注解

运行时,通过反射获得,使用范围:属性、方法上

/**
 * @Author: wwwppp
 * @Date: 2020-9-14 22:01
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.METHOD})
public @interface MyAnno {

    String value() default "Tom";

}

实体类

/**
 * @Author: wwwppp
 * @Date: 2020-9-14 22:06
 */
public class User {

    @MyAnno
    private String defaultName;

    @MyAnno(value = "jack")
    private String name;

    @MyAnno(value = "123")
    private String phone;

    @MyAnno(value = "18")
    private Integer age;

    @MyAnno(value = "log")
    public String log(){
        return "log";
    }

}

实现

/**
 * @Author: wwwppp
 * @Date: 2020-9-14 22:08
 */
public class Test {

    public static void main(String[] args) {

    /*
    getFields:只能访问public属性及继承到的public属性
    getDeclaredFields:只能访问到本类的属性,不能访问继承到的属性

    getMethods:只能访问public方法及继承到的public方法
    getDeclaredMethods:只能访问到本类的方法,不能访问继承到的方法

    getConstructors:只能访问public构造函数及继承到的public构造函数
    getDeclaredConstructors:只能访问到本类的构造函数,不能访问继承到的构造函数
    */

        Method[] methods = User.class.getMethods();
        //Field[] fields = User.class.getFields();
        Field[] fields = User.class.getDeclaredFields();

        for (Field field : fields) {
            MyAnno annotation = field.getAnnotation(MyAnno.class);
            if (annotation != null) {
                System.out.println("field=" + annotation.value());
            }
        }
        for (Method method : methods) {
            MyAnno annotation = method.getAnnotation(MyAnno.class);
            if (annotation != null) {
                System.out.println("method=" + annotation.value());
            }
        }

    }

}

结果

field=Tom
field=jack
field=123
field=18
method=log