自定义注解

自定义注解

1. 元注解

​ 元注解:用于修饰注解。

​ 四种元注解:

① @Retention: 只能用于修饰一个 Annotation 定义, 用于指定该 Annotation 的生命周期, @Rentention 包含一个 RetentionPolicy 类型的成员变量。

RetentionPolicy.SOURCE:在源文件中有效;
RetentionPolicy.CLASS:在class文件中有效;
RetentionPolicy.RUNTIME:在运行时有效;
@Target: 用于修饰 Annotation 定义, 用于指定被修饰的 Annotation 能用于修饰哪些程序元素。我的理解是可以在哪里使用这个注解。

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,  //任何类型变量的声明语句中

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE    //使用类型的任何语句中
}

③@Documented: 用于指定被该元 Annotation 修饰的 Annotation 类将被javadoc 工具提取成文档。默认情况下,javadoc是不包括注解的。
④@Inherited: 被它修饰的 Annotation 将具有继承性。如果某个类使用了被@Inherited 修饰的 Annotation, 则其子类将自动具有该注解。

2.自定义注解

注解如下:

@Target({ElementType.METHOD,ElementType.TYPE})  //可在方法和类中使用它
@Retention(RetentionPolicy.RUNTIME)  //运行时有效
public @interface MyAnno {

    int value() default 1;
}

使用注解:

@MyAnno(value = 2)
public class Main {

    @MyAnno(value = 2)
    public static void main(String[] args) {

        Class<Main> mainClass = Main.class;
        MyAnno annotation = mainClass.getAnnotation(MyAnno.class);
        int value = annotation.value(); //获取注解的值
        System.out.println(value);
    }
}

运行截图:

posted @ 2020-05-19 20:38  pavi  阅读(172)  评论(0编辑  收藏  举报