注解

java 注解,從名字上看是注釋,解釋。但功能卻不僅僅是注釋那么簡(jiǎn)單。注解(Annotation) 為我們?cè)诖a中添加信息提供了一種形式化的方法,是我們可以在稍后 某個(gè)時(shí)刻方便地使用這些數(shù)據(jù)(通過 解析注解 來使用這些數(shù)據(jù)),常見的作用有以下幾種:

  • 生成文檔。這是最常見的,也是java 最早提供的注解。常用的有@see @param @return 等
  • 跟蹤代碼依賴性,實(shí)現(xiàn)替代配置文件功能。比較常見的是spring 2.5 開始的基于注解配置。作用就是減少配置?,F(xiàn)在的框架基本都使用了這種配置來減少配置文件的數(shù)量。
  • 在編譯時(shí)進(jìn)行格式檢查。如@override 放在方法前,如果你這個(gè)方法并不是覆蓋了超類方法,則編譯時(shí)就能檢查出。

包 java.lang.annotation 中包含所有定義自定義注解所需用到的原注解和接口。如接口 java.lang.annotation.Annotation 是所有注解繼承的接口,并且是自動(dòng)繼承,不需要定義時(shí)指定,類似于所有類都自動(dòng)繼承Object。

該包同時(shí)定義了四個(gè)元注解,Documented,Inherited,Target(作用范圍,方法,屬性,構(gòu)造方法等),Retention(生命范圍,源代碼,class,runtime)。


四個(gè)元注解分別是:@Target,@Retention,@Documented,@Inherited

@Target : 表示該注解用于什么地方,可能的值在枚舉類 ElemenetType 中,包括:
ElemenetType.CONSTRUCTOR 構(gòu)造器聲明
ElemenetType.FIELD      域聲明(包括 enum 實(shí)例)
ElemenetType.LOCAL_VARIABLE 局部變量聲明
ElemenetType.METHOD    方法聲明
ElemenetType.PACKAGE    包聲明
ElemenetType.PARAMETER 參數(shù)聲明
ElemenetType.TYPE      類,接口(包括注解類型)或enum聲明

@Retention : 表示在什么級(jí)別保存該注解信息??蛇x的參數(shù)值在枚舉類型 RetentionPolicy 中,包括:
RetentionPolicy.SOURCE     注解將被編譯器丟棄
RetentionPolicy.CLASS       注解在class文件中可用,但會(huì)被VM丟棄
RetentionPolicy.RUNTIME     VM將在運(yùn)行期也保留注釋,因此可以通過反射機(jī)制讀取注解的信息。

@Documented : 將此注解包含在 javadoc 中 ,它代表著此注解會(huì)被javadoc工具提取成文檔。在doc文檔中的內(nèi)容會(huì)因?yàn)榇俗⒔獾男畔?nèi)容不同而不同。相當(dāng)與@see,@param 等。

@Inherited : 在您定義注解后并使用于程序代碼上時(shí),預(yù)設(shè)上父類別中的注解并不會(huì)被繼承至子類別中,您可以在定義注解時(shí)加上java.lang.annotation.Inherited 限定的Annotation,這讓您定義的Annotation型別被繼承下來。注意注解繼承只針對(duì)class 級(jí)別注解有效(這段建議看完全文后在來回顧)。 多說無益,下面就一步步從零開始建一個(gè)我們自己的注解。


TestA注解類

package annotation.test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 定義注解 Test <br>
 * 為方便測(cè)試:注解目標(biāo)為類 方法,屬性及構(gòu)造方法<br> 
 * 注解中含有三個(gè)元素 id ,name和 gid;  <br>
 * id 元素 有默認(rèn)值 0 <br>
 */ 
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD,ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface TestA {
    String name() ;
    int id() default 0;
    Class<Long> gid();
}

UserAnnotation測(cè)試類

package annotation.test;

import java.util.HashMap;
import java.util.Map;
/**
 * 這個(gè)類專門用來測(cè)試注解使用
 */

@TestA(name="type",gid=Long.class)
// 使用了類注解
public class UserAnnotation {
    @TestA(name="param",id=1,gid=Long.class) // 使用了類成員注解
    private Integer age;

    @TestA(name="construct",id=2,gid=Long.class)// 使用了構(gòu)造方法注解
    public UserAnnotation() {
    }

    @TestA(name="public method", id=3, gid=Long.class)// 使用了 public 方法注解
    public void a() {
        Map<String, String> m = new HashMap<String, String>(0);
    }

    @TestA(name="protected method", id=4, gid=Long.class)//protected 方法注解
    protected void b() { 
        Map<String, String> m = new HashMap<String, String>(0);
    }
    
    @TestA(name="private method " , id = 5, gid=Long.class) // private 方法注解
    private void c(){
        Map<String, String> m = new HashMap<String, String>(0);
    }
    
    public void b(Integer a){ 
    }
}

將注解讀取出來

package annotation.test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ParseAnnotation {

    /**
     * 簡(jiǎn)單打印出UserAnnotation 類中所使用到的類注解
     * 該方法只打印了 Type 類型的注解
     * @throws ClassNotFoundException
     */
    public static void parseTypeAnnotation() throws ClassNotFoundException{
        Class clazz = Class.forName("annotation.test.UserAnnotation");
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            TestA testA = (TestA) annotation;
            System.out.println("type name = "+clazz.getName() + "  |  id = " + testA.id() + "  |  name = " + testA.name() + "  |                      gid = " + testA.gid());
        }
    }
    
    /**
     * 簡(jiǎn)單打印出UserAnnotation 類中所使用到的方法注解
     * 該方法只打印了 Method 類型的注解
     * @throws ClassNotFoundException
     */
    public static void parseMethodAnnotation() throws ClassNotFoundException{
        Method[] methods = UserAnnotation.class.getDeclaredMethods();
        for (Method method : methods) {
             /* 
             * 判斷方法中是否有指定注解類型的注解 
             */  
            boolean hasAnnotation = method.isAnnotationPresent(TestA.class);
            if(hasAnnotation){
                TestA annotation = method.getAnnotation(TestA.class);
                System.out.println("method name = " + method.getName() + "  |  id = " +
                        annotation.id() + "  |  description = " + annotation.name() + "  |  gid = " + annotation.gid());
            }
        }
    }
    
    /**
     * 簡(jiǎn)單打印出UserAnnotation 類中所使用到的構(gòu)造方法注解
     * 該方法只打印了 構(gòu)造方法 類型的注解
     * @throws ClassNotFoundException
     */
    public static void parseConstructAnnotation()  throws ClassNotFoundException{
        Constructor[] constructors = UserAnnotation.class.getConstructors();
        for (Constructor constructor : constructors) {
            /* 
             * 判斷構(gòu)造方法中是否有指定注解類型的注解 
             */  
            boolean hasAnnotation = constructor.isAnnotationPresent(TestA.class);
            if(hasAnnotation){
                 /* 
                 * 根據(jù)注解類型返回方法的指定類型注解 
                 */
                TestA annotation = (TestA) constructor.getAnnotation(TestA.class);
                System.out.println("constructor = " + constructor.getName()  
                        + "   |   id = " + annotation.id() + "  |  description = "  
                        + annotation.name() + "  |   gid= "+annotation.gid());
            }
        }
    }
    
    /**
     * 簡(jiǎn)單打印出UserAnnotation 類中所使用到的字段注解
     * 該方法只打印了 Method 類型的注解
     * @throws ClassNotFoundException
     */
    public static void parseFieldAnnotation() throws ClassNotFoundException{
        Field[] fields = UserAnnotation.class.getDeclaredFields();
        for (Field field : fields) {
            boolean hasAnnotation = field.isAnnotationPresent(TestA.class);
            if(hasAnnotation){
                TestA annotation = field.getAnnotation(TestA.class);
                System.out.println("Field = " + field.getName()  
                        + "  |  id = " + annotation.id() + "  |  description = "  
                        + annotation.name() + "  |  gid= "+annotation.gid());
            }
        }
    }
    
    public static void main(String[] args) throws ClassNotFoundException {
        System.out.println("------------------------------解析Type注解----------------------------------------------------------");
        parseTypeAnnotation();
        System.out.println("------------------------------解析Method注解-------------------------------------------------------");
        parseMethodAnnotation();
        System.out.println("------------------------------解析構(gòu)造方法(Construct)注解------------------------------------------");
        parseConstructAnnotation();
        System.out.println("------------------------------解析字段(Field)注解-----------------------------------------------------");
        parseFieldAnnotation();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容