[JavaSE]->{注解和反射03}-->元注解

元注解

写在前面:本篇博客只用于学习笔记


  • 元注解的作用就是负责注解其他注解 , Java定义了4个标准的meta-annotation类型,他们被用来提供
    对其他annotation类型作说明 .
  • 这些类型和它们所支持的类在java.lang.annotation包中可以找到 .( @Target , @Retention ,@Documented , @Inherited )
    • @Target : 用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
    • @Retention : 表示需要在什么级别保存该注释信息 , 用于描述注解的生命周期
      • SOURCE < CLASS < RUNTIME
    • @Document:说明该注解将被包含在javadoc中
    • @Inherited:说明子类可以继承父类中的该注解
import java.lang.annotation.*;

public class Test2 {
    @MyAnnotation
    public void test(){

    }
    
}

//定义一个注解
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Inherited
@Documented
@interface MyAnnotation{}

补充:

  1. 枚举类型:ElementType
package java.lang.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
}

  1. 枚举类型:RetentionPolicy
package java.lang.annotation;

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
}


写在后面:
参考资料:【狂神说Java】注解和反射

你可能感兴趣的:(【1】JavaSE,java)