RetentionPolicy

  在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. 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章