注解(Annotation)

注解(Annotation)是java的重要组成部分,用于标记,从jdk1.5开始引入的新特性。

Jdk早起引入的注解有:@Deprecated,@Override,@SuppressWarnings

 简单注解格式(以spring Autowired为例)

 1 @Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
 2 @Retention(RetentionPolicy.RUNTIME)
 3 @Documented
 4 public @interface Autowired {
 5 
 6     /**
 7      * Declares whether the annotated dependency is required.
 8      * <p>Defaults to {@code true}.
 9      */
10     boolean required() default true;
11 
12 }

注解是一冲标记,@Target代表可以标记的类型,可以标记在ElementType枚举出的类型

 1 public enum ElementType {
 2     /** Class, interface (including annotation type), or enum declaration */
 3     TYPE,
 4 
 5     /** Field declaration (includes enum constants) */
 6     FIELD,
 7 
 8     /** Method declaration */
 9     METHOD,
10 
11     /** Formal parameter declaration */
12     PARAMETER,
13 
14     /** Constructor declaration */
15     CONSTRUCTOR,
16 
17     /** Local variable declaration */
18     LOCAL_VARIABLE,
19 
20     /** Annotation type declaration */
21     ANNOTATION_TYPE,
22 
23     /** Package declaration */
24     PACKAGE,
25 
26     /**
27      * Type parameter declaration
28      *
29      * @since 1.8
30      */
31     TYPE_PARAMETER,
32 
33     /**
34      * Use of a type
35      *
36      * @since 1.8
37      */
38     TYPE_USE
39 }

@Retention代表作用域RetentionPolicy

 1 public enum RetentionPolicy {
 2     /**
 3      * Annotations are to be discarded by the compiler.
 4      */
 5     SOURCE,
 6 
 7     /**
 8      * Annotations are to be recorded in the class file by the compiler
 9      * but need not be retained by the VM at run time.  This is the default
10      * behavior.
11      */
12     CLASS,
13 
14     /**
15      * Annotations are to be recorded in the class file by the compiler and
16      * retained by the VM at run time, so they may be read reflectively.
17      *
18      * @see java.lang.reflect.AnnotatedElement
19      */
20     RUNTIME
21 }

包换三种类型,分别对应的有效作用域是.java文件、.class文件、内存中的字节码。

javac将java源文件编译成class文件会去掉SOURCE的注解,类加载器将class文件加载到内存中会去掉CLASS的注解,运行期RUNTIME有效的注解会一直存在。

注解中包换一些value,例如required,boolean类型,默认值为true。

运行期获取注解

1 Autowired autowired= (Autowired)Object.class.getAnnotation(Autowired.class);
原文地址:https://www.cnblogs.com/avalon-merlin/p/10509856.html