




已閱讀5頁,還剩10頁未讀, 繼續(xù)免費(fèi)閱讀
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
JAVA 注解的幾大作用及使用方法詳解注解(Annotation)1、Annotation的工作原理:JDK5.0中提供了注解的功能,允許開發(fā)者定義和使用自己的注解類型。該功能由一個定義注解類型的語法和描述一個注解聲明的語法,讀取注解的API,一個使用注解修飾的class文件和一個注解處理工具組成。Annotation并不直接影響代碼的語義,但是他可以被看做是程序的工具或者類庫。它會反過來對正在運(yùn)行的程序語義有所影響。Annotation可以從源文件、class文件或者在運(yùn)行時通過反射機(jī)制多種方式被讀取。常見的作用有以下幾種:1,生成文檔。這是最常見的,也是java 最早提供的注解。常用的有see param return 等2,跟蹤代碼依賴性,實(shí)現(xiàn)替代配置文件功能。比較常見的是spring 2.5 開始的基于注解配置。作用就是減少配置?,F(xiàn)在的框架基本都使用了這種配置來減少配置文件的數(shù)量。3,在編譯時進(jìn)行格式檢查。如override 放在方法前,如果你這個方法并不是覆蓋了超類方法,則編譯時就能檢查出。*interface用來聲明一個注解,其中的每一個方法實(shí)際上是聲明了一個配置參數(shù)。*方法的名稱就是參數(shù)的名稱,返回值類型就是參數(shù)的類型。*可以通過default來聲明參數(shù)的默認(rèn)值。父類,接口Java.lang.annotation包 java.lang.annotation 中包含所有已定義或自定義注解所需用到的原注解和接口。如接口 java.lang.annotation.Annotation 是所有注解繼承的接口,并且是自動繼承,不需要定義時指定,類似于所有類都自動繼承Object。該包同時定義了四個元注解;常見注解Override注解:注釋類型 OverrideTarget(value=METHOD)Retention(value=SOURCE)public interface OverrideOverride注解表示子類要重寫父類的對應(yīng)方法。下面是一個使用Override注解的例子:class A private String id; A(String id) this.id = id; Override public String toString() return id; Deprecated注解:注釋類型 DeprecatedDocumentedRetention(value=RUNTIME)public interface DeprecatedDeprecated注解表示方法是不被建議使用的。下面是一個使用Deprecated注解的例子:class A private String id; A(String id) this.id = id; Deprecated public void execute() System.out.println(id); public static void main(String args) A a = new A(a123); a.execute(); SuppressWarnings注解:注釋類型 SuppressWarningsTarget(value=TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE)Retention(value=SOURCE)public interface SuppressWarnings指示應(yīng)該在注釋元素(以及包含在該注釋元素中的所有程序元素)中取消顯示指定的編譯器警告。注意,在給定元素中取消顯示的警告集是所有包含元素中取消顯示的警告的超集。例如,如果注釋一個類來取消顯示某個警告,同時注釋一個方法來取消顯示另一個警告,那么將在此方法中同時取消顯示這兩個警告。下面是一個使用SuppressWarnings注解的例子:SuppressWarnings(unchecked)public static void main(String args) List list = new ArrayList(); list.add(abc);自定義注解使用interface自定義注解時,自動繼承了java.lang.annotation.Annotation接口,由編譯程序自動完成其他細(xì)節(jié)。在定義注解時,不能繼承其他的注解或接口。1,自定義最簡單的注解:public interface MyAnnotation 使用自定義注解:public class AnnotationTest2 MyAnnotation public void execute() System.out.println(method); 2,添加變量:public interface MyAnnotation String value1();使用自定義注解:public class AnnotationTest2 MyAnnotation(value1=abc) public void execute() System.out.println(method); 添加默認(rèn)值:public interface MyAnnotation String value1() default abc;3、多變量使用枚舉:public interface MyAnnotation String value1() default abc; MyEnum value2() default MyEnum.Sunny;enum MyEnum Sunny,Rainy使用自定義注解:public class AnnotationTest2 MyAnnotation(value1=a, value2=MyEnum.Sunny) public void execute() System.out.println(method); 4、數(shù)組變量:public interface MyAnnotation String value1() default abc;使用自定義注解:public class AnnotationTest2 MyAnnotation(value1=a,b) public void execute() System.out.println(method); 當(dāng)注解中使用的屬性名為value時,對其賦值時可以不指定屬性的名稱而直接寫上屬性值接口;除了value意外的變量名都需要使用name=value的方式賦值。5、限定注解的使用:限定注解使用Target。DocumentedRetention(value=RUNTIME)Target(value=ANNOTATION_TYPE)public interface Target指示注釋類型所適用的程序元素的種類。如果注釋類型聲明中不存在 Target 元注釋,則聲明的類型可以用在任一程序元素上。如果存在這樣的元注釋,則編譯器強(qiáng)制實(shí)施指定的使用限制。 例如,此元注釋指示該聲明類型是其自身,即元注釋類型。它只能用在注釋類型聲明上:Target(ElementType.ANNOTATION_TYPE) public interface MetaAnnotationType . 此元注釋指示該聲明類型只可作為復(fù)雜注釋類型聲明中的成員類型使用。它不能直接用于注釋:Target() public interface MemberType . 這是一個編譯時錯誤,它表明一個 ElementType 常量在 Target 注釋中出現(xiàn)了不只一次。例如,以下元注釋是非法的:Target(ElementType.FIELD, ElementType.METHOD, ElementType.FIELD) public interface Bogus . public enum ElementTypeextends Enum程序元素類型。此枚舉類型的常量提供了 Java 程序中聲明的元素的簡單分類。這些常量與 Target 元注釋類型一起使用,以指定在什么情況下使用注釋類型是合法的。ANNOTATION_TYPE注釋類型聲明CONSTRUCTOR構(gòu)造方法聲明FIELD字段聲明(包括枚舉常量)LOCAL_VARIABLE局部變量聲明METHOD方法聲明PACKAGE包聲明PARAMETER參數(shù)聲明TYPE類、接口(包括注釋類型)或枚舉聲明注解的使用限定的例子:Target(ElementType.METHOD)public interface MyAnnotation String value1() default abc;元注解元注解是指注解的注解。包括 Retention Target Document Inherited四種。Target 表示該注解用于什么地方,可能的值在枚舉類 ElemenetType 中,包括: Target(ElementType.TYPE) /接口、類、枚舉、注解Target(ElementType.FIELD) /字段、枚舉的常量Target(ElementType.METHOD) /方法Target(ElementType.PARAMETER) /方法參數(shù)Target(ElementType.CONSTRUCTOR) /構(gòu)造函數(shù)Target(ElementType.LOCAL_VARIABLE)/局部變量Target(ElementType.ANNOTATION_TYPE)/注解 Target(ElementType.PACKAGE) /包 packag注解必須在package-info.java 中聲明Retention 表示在什么級別保存該注解信息??蛇x的參數(shù)值在枚舉類型 RetentionPolicy 中,包括: Retention(RetentionPolicy.SOURCE) /注解僅存在于源碼中,在class字節(jié)碼文件中不包含 Retention(RetentionPolicy.CLASS) / 默認(rèn)的保留策略,注解會在class字節(jié)碼文件中存在,但運(yùn)行時無法獲得, Retention(RetentionPolicy.RUNTIME) / 注解會在class字節(jié)碼文件中存在,在運(yùn)行時可以通過反射獲取到Documented 將此注解包含在 javadoc 中 ,它代表著此注解會被javadoc工具提取成文檔。在doc文檔中的內(nèi)容會因?yàn)榇俗⒔獾男畔?nèi)容不同而不同。相當(dāng)與see,param 等。 Inherited 允許子類繼承父類中的注解TargetTarget用來聲明注解可以被添加在哪些類型的元素上,如類型、方法和域等。 例:Target(TYPE,METHOD,FIELD,CONSTRUCTOR)public interface TestA /這里定義了一個空的注解。 這個類專門用來測試注解使用TestA /使用了類注解public class UserAnnotation TestA /使用了類成員注解 private Integer age; TestA /使用了構(gòu)造方法注解 public UserAnnotation() TestA /使用了類方法注解 public void a() TestA /使用了局部變量注解 Map m = new HashMap(0); TestA /使用了方法參數(shù)注解 public void b(TestA Integer a) RetentionRetention用來聲明注解的保留策略,有CLASS、RUNTIME和SOURCE這三種,分別表示注解保存在類文件、JVM運(yùn)行時刻和源代碼中。只有當(dāng)聲明為RUNTIME的時候,才能夠在運(yùn)行時刻通過反射API來獲取到注解的信息。無屬性注解Retention 參數(shù) RetentionPolicy。這個注解還沒有特殊的屬性值。 簡單演示下如何使用: import java.lang.annotation.ElementType;import java.lang.annotation.Target;/* * 定義注解 Test * 首先使用ElementType.TYPE(需要在package-info.java中聲明)* 運(yùn)行級別定為 運(yùn)行時,以便后面測試解析 */ Target(ElementType.TYPE)Retention(RetentionPolicy.RUNTIME)public interface TestA 有屬性注解interface用來聲明一個注解,其中的每一個方法實(shí)際上是聲明了一個配置參數(shù)。方法的名稱就是參數(shù)的名稱,返回值類型就是參數(shù)的類型(返回值類型只能是基本類型、Class、String、enum)。可以通過default來聲明參數(shù)的默認(rèn)值。代碼:/* * 定義注解 Test * 為方便測試:注解目標(biāo)為類 方法,屬性及構(gòu)造方法 * 注解中含有三個元素 id ,name和 gid; * id 元素 有默認(rèn)值 0*/ Target(TYPE,METHOD,FIELD,CONSTRUCTOR)Retention(RetentionPolicy.RUNTIME)public interface TestA String name();int id() default 0;Class gid();測試類import java.util.HashMap;import java.util.Map; /* 這個類專門用來測試注解使用*/ 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 void a()Map m = new HashMap(0);TestA(name=protected method,id=4,gid=Long.class) /類方法注解protected void b()Map m = new HashMap(0);TestA(name=private method,id=5,gid=Long.class) /類方法注解private void c()Map m = new HashMap(0);public void b(Integer a) 讀取定義注解內(nèi)容import java.lang.annotation.Annotation;import java.lang.reflect.Constructor;import java.lang.reflect.Method; public class ParseAnnotation /*A 簡單打印出UserAnnotation 類中所使用到的類注解* 該方法只打印了 Type 類型的注解* throws ClassNotFoundException*/public static void parseTypeAnnotation() throws ClassNotFoundException Class clazz = Class.forName(com.tmser.annotation.UserAnnotation); Annotation annotations = clazz.getAnnotations(); for (Annotation annotation : annotations) TestA testA = (TestA)annotation;System.out.println(id= +testA.id()+; name= +testA.name()+; gid = +testA.gid(); /結(jié)果為id=0;name=type;gid =classjava.lang.Long/* B簡單打印出UserAnnotation 類中所使用到的方法注解* 該方法只打印了 Method 類型的注解* throws ClassNotFoundException*/public static void parseMethodAnnotation()Method methods = UserAnnotation.class.getDeclaredMethods(); for (Method method : methods) / 判斷方法中是否有指定注解類型的注解 boolean hasAnnotation = method.isAnnotationPresent(TestA.class); if (hasAnnotation) /根據(jù)注解類型返回方法的指定類型注解 TestA annotation = method.getAnnotation(TestA.class); System.out.println(method = + method.getName() + ; id = + annotation.id() + ; description = + () + ; gid= +annotation.gid(); method = c ; id = 5 ; description = private method; gid= class java.lang.Longmethod = a ; id = 3 ; description = public method; gid= class java.lang.Longmethod = b ; id = 4 ; description = protected method; gid= class java.lang.Long/* C簡單打印出UserAnnotation 類中所使用到的構(gòu)造方法注解* 該方法只打印了 Method 類型的注解* throws ClassNotFoundException*/public static void parseConstructAnnotation()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 = + () + ; gid= +annotation.gid(); constructor=com.tmser.annotation.UserAnnotation;id=2;description =construct;gid=classjava.lang.Longpublic static void main(String args) throws ClassNotFoundException parseTypeAnnotation();parseMethodAnnotation();parseConstructAnnotation();/field是一樣的,省略之Documented 在幫助文檔中加入注解:要想在制作JavaDoc文件的同時將注解信息加入到API文件中,可以使用java.lang.annotation.Documented。在自定義注解中聲明構(gòu)建注解文檔:Documentedpublic interface MyAnnotation String value1() default abc;使用自定義注解:public class AnnotationTest2 MyAnnotation(value1=a,b) public void execute() System.out.println(method); Inherited 在注解中使用繼承:默認(rèn)情況下注解并不會被繼承到子類中,可以在自定義注解時加上java.lang.annotation.Inherited注解聲明使用繼承。DocumentedRetention(value=RUNTIME)Target(value=ANNOTATION_TYPE)public interface Inherited指示注釋類型被自動繼承。如果在注釋類型聲明中存在 Inherited 元注釋,并且用戶在某一類聲明中查詢該注釋類型,同時該類聲明中沒有此類型的注釋,則將在該類的超類中自動查詢該注釋類型。此過程會重復(fù)進(jìn)行,直到找到此類型的注釋或到達(dá)了該類層次結(jié)構(gòu)的頂層 (Object) 為止。如果沒有超類具有該類型的注釋,則查詢將指示當(dāng)前類沒有這樣的注釋。注意,如果使用注釋類型注釋類以外的任何事物,此元注釋類型都是無效的。還要注意,此元注釋僅促成從超類繼承注釋;對已實(shí)現(xiàn)接口的注釋無效。自定義注解案例實(shí)例1:下面是使用反射讀取RUNTIME保留策略的Annotation信息的例子:自定義注解:Retention(RetentionPolicy.RUNTIME)public interface MyAnnotation String value1() default abc;使用自定義注解:public class AnnotationTest2 MyAnnotation(value1=a,b) Deprecated public void execute() System.out.println(method); 讀取注解中的信息:public static void main(String args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException AnnotationTest2 annotationTest2 = new AnnotationTest2(); /獲取AnnotationTest2的Class實(shí)例 Class c = AnnotationTest2.class; /獲取需要處理的方法Method實(shí)例 Method method = c.getMethod(execute, new Class); /判斷該方法是否包含MyAnnotation注解 if(method.isAnnotationPresent(MyAnnotation.class) /獲取該方法的MyAnnotation注解實(shí)例 MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class); /執(zhí)行該方法 method.invoke(annotationTest2, new Object); /獲取myAnnotation String value1 = myAnnotation.value1(); System.out.println(value10); /獲取方法上的所有注解 Annotation annotations = method.getAnnotations(); for(Annotation annotation : annotations) System.out.println(annotation); 實(shí)例2:DocumentedTarget(ElementType.TYPE,ElementType.METHOD)Retention(RetentionPolicy.RUNTIME)public interface Yts public enum YtsTypeutil,entity,service,model; public YtsType classType() default YtsType.util;Documented Retention(RetentionPolicy.RUNTIME) Target(ElementType.METHOD) Inherited public interface HelloWorld public String name()default ; public class ParseAnnotation public void parseMethod(Class clazz) throws IllegalArgumentException, IllegalAccessException,InvocationTargetException,SecurityException, NoSuchMethodException, InstantiationException Object obj = clazz.getConstructor(new Class).newInstance(new Object); for(Method method : clazz.getDeclaredMethods() HelloWorld say = method.getAnnotation(HelloWorld.class); String name = ; if(say != nul
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 在2025年注冊土木工程師中尋找試題及答案的價值
- 中國阿膠行業(yè)市場發(fā)展現(xiàn)狀及前景趨勢與投資分析研究報告2025-2028版
- 中國鋰鈷氧化物行業(yè)市場發(fā)展前景及發(fā)展趨勢與投資戰(zhàn)略研究報告2025-2028版
- 兒科手足口病試題及答案
- 中國螺螄肉行業(yè)市場發(fā)展前景及發(fā)展趨勢與投資戰(zhàn)略研究報告2025-2028版
- 中國童車行業(yè)市場發(fā)展現(xiàn)狀及前景趨勢與投資分析研究報告2025-2028版
- 中國科技地產(chǎn)行業(yè)市場發(fā)展分析及發(fā)展趨勢與投資機(jī)會研究報告2025-2028版
- 中國電鍍絞肉機(jī)行業(yè)市場發(fā)展前景及發(fā)展趨勢與投資戰(zhàn)略研究報告2025-2028版
- 吸納創(chuàng)業(yè)者反饋的政策試題及答案
- 2024年福建廈門夏商集團(tuán)有限公司招聘真題
- 小學(xué)女子足球隊(duì)訓(xùn)練計劃
- FZ∕T 74001-2020 紡織品 針織運(yùn)動護(hù)具
- 人體常見病 知到智慧樹網(wǎng)課答案
- 幼兒詩歌《家》課件
- 2024年4月自考00043經(jīng)濟(jì)法概論(財經(jīng)類)試題
- MOOC 大話法醫(yī)學(xué)-華中科技大學(xué) 中國大學(xué)慕課答案
- 汽車租賃服務(wù)投標(biāo)方案(技術(shù)方案2)
- 腹瀉便秘課件
- 高考藝考文化課培訓(xùn)
- HG-T 20583-2020 鋼制化工容器結(jié)構(gòu)設(shè)計規(guī)范
- 2024年02月中國僑聯(lián)直屬事業(yè)單位招考聘用筆試歷年參考題庫(考點(diǎn)甄選)含答案帶詳解附后
評論
0/150
提交評論