在java开发过程中,我们可能经常点进去一个注解(如Targe),看到其上会有@Retention(RetentionPolicy.RUNTIME)。RetentionPolicy是个枚举类,今天想写一下RetentionPolicy这个枚举类都有哪些东西。
一、文件头:
如下图,首先是oracle版权声明和java包名,说明肯定不是第三方工具类文件(有点废话)。
/*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.lang.annotation;
二、接着是枚举类的注释,下面是大概意思:
注解保留策略。该枚举类所枚举的常量类型,描述了几种注解保留策略。这些策略要和元注解:Retention联合使用以描述
该策略所修饰的注解会被保留多久。
/**
* Annotation retention policy. The constants of this enumerated type
* describe the various policies for retaining annotations. They are used
* in conjunction with the {@link Retention} meta-annotation type to specify
* how long annotations are to be retained.
*
* @author Joshua Bloch
* @since 1.5
*/
三、策略类型:
1.SOURCE
在编译的时候,注解会被编译程序丢弃。
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
2.CLASS
在编译的时候,注解会被编译程序记录在class文件中,但是在虚拟机运行的时候不会被保留。这是默认的保留策略。
/**
* 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,
3.RUNTIME
注解不但会被编译程序记录在class文件中,而且虚拟机运行的时候也会保留,
所以被该策略修饰的注解能通过java反射机制读取。
/**
* 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
四、RetentionPolicy源码
/*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.lang.annotation;
/**
* Annotation retention policy. The constants of this enumerated type
* describe the various policies for retaining annotations. They are used
* in conjunction with the {@link Retention} meta-annotation type to specify
* how long annotations are to be retained.
*
* @author Joshua Bloch
* @since 1.5
*/
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版本如下
$ java -version
java version "1.8.0_152"
Java(TM) SE Runtime Environment (build 1.8.0_152-b16)
Java HotSpot(TM) 64-Bit Server VM (build 25.152-b16, mixed mode)
Copyright © 2018 Ansel. All rights reserved.