Java元注解和自定义注解

Java元注解和自定义注解

元注解

除了直接使用JDK 定义好的注解,我们还可以自定义注解,在JDK 1.5中提供了4个标准的用来对注解类型进行注解的注解类,我们称之为 meta-annotation(元注解),他们分别是:

  • @Target

  • @Retention

  • @Documented

  • @Inherited

    我们可以使用这4个元注解来对我们自定义的注解类型进行注解。

    @Target

    作用:描述注解的使用范围

    在定义注解类时使用了@Target 能够更加清晰的知道它能够被用来修饰哪些对象,它的取值范围定义在ElementType 枚举中

    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
    }
    

    @Retention

    作用:描述注解保留的时间范围(即:被描述的注解在它所修饰的类中可以被保留到何时)

    Reteniton注解用来限定那些被它所注解的注解类在注解到其他类上以后,可被保留到何时,一共有三种策略,定义在RetentionPolicy枚举中。

    //RUNTIME>CLASS>SOURCE
    public enum RetentionPolicy {
        /**
         * Annotations are to be discarded by the compiler.
         */
        SOURCE,
    
        /**
         * Annotations are to be recorded in the class file by the compiler
         * but need not be retained by the VM at run time.  This is the default
         * behavior.
         */
        CLASS,
    
        /**
         * Annotations are to be recorded in the class file by the compiler and
         * retained by the VM at run time, so they may be read reflectively.
         *
         * @see java.lang.reflect.AnnotatedElement
         */
        RUNTIME
    }
    

    一般自定义的注解使用的都适合RUNTIME即保留到运行时

    @Documented

    作用:描述在使用 javadoc 工具为类生成帮助文档时是否要保留其注解信息,加上就是说明在生成的帮助文档上保留注解信息。

    @Inherited

    使被它修饰的注解具有继承性(如果某个类使用了被@Inherited修饰的注解,则其子类将自动具有该注解)。

自定义注解

使用@interface来自定义一个注解,会自动的继承java.lang.annotation.Annotation接口。同时在自定义注解上加上元注解,常用的是@Target和@Retention。

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
    /* 定义的是注解的参数
     * 格式为 :参数类型 + 参数名 ()
     * 当注解的参数只有一个值的时候,参数名建议使用value(),同时在引用参数的地方可以不写参数名(也只有参数名为value的时候才可以,不然会报错)
     */
    String name() default "";
    String[] hobbies() default {"play","eat"};
}
posted @ 2021-04-07 09:52  newobject1024  阅读(297)  评论(0)    收藏  举报