Notes - four kinds of meta-annotation

Java provides four modifications for custom annotation of metadata annotation:
@ Target, @ Retention, @ of Documented and @Inherited

@Target:

Modified for specifying custom annotations for modifying only the program which elements common attribute values:
ElementType.FIELD: Global attributes applied
ElementType.METHOD: Method applied
ElementType.PARAMETER: Method parameters apply
ElementType. tYPE: applied to a class, interface, or enum declaration

@Retention

@Retention: for specifying custom annotations can be modified to retain long, the metadata annotation has the following property values:
RetentionPolicy.SOURCE: the compiler discards the modified annotation.
RetentionPolicy.CLASS: default value, the compiler will record notes in class file when you run a Java program, the virtual machine is no longer reserved Note;
RetentionPolicy.RUNTIME: compiler will record notes in class files when running java program when, virtual machine reserved Note, the program can obtain the annotation by reflection;

@Documented

Javadoc command is executed, the modified meta-annotation custom annotation in the document will be generated

@Inherited

If the parent class notes used there @Inherited modification, the subclass can inherit the notes, or can not be inherited.

Comprehensive examples:

@Target(ElementType.TYPE)//只能应用于类
@Retention(RetentionPolicy.RUNTIME)//由于是.RUNTIME,所以注解可以作用到运行时,所以控制台可以输出。默认为.CLASS,即作用到编译为class文件,无法作用到程序运行时,即无法作用到控制台。
@Inherited//如果不写该注解,则子类无法继承该注解,则控制台不会输出
public @interface Parent{
    String key();
    String value();
}

@Parent(key = "name", value = "张三")//自定义注解
public class Parent {

}

public class Son extends Parent {
    public static void main(String[] args) {
        Annotation[] annotations = Son.class.getAnnotations();
        // 控制台输出[@venus.Parent(key=name, value=张三)]
        System.out.println(Arrays.toString(annotations));
    }
}
Published 101 original articles · won praise 3 · Views 2248

Guess you like

Origin blog.csdn.net/S_Tian/article/details/103887889