注解的使用
1.概述
注解: Java核心技術(shù)上一通操作猛如虎,我還是沒懂,目前的理解大概就是,比如在一個方法上添加了注解,那么運(yùn)行的時候,就會對這個方法進(jìn)行相應(yīng)的處理,還是不解釋了…直接上手
又經(jīng)過一頓操作猛如虎之后,我悟了,注解本身不會對代碼產(chǎn)生影響,但是注解本身是有值的,根據(jù)這些取值,通過對當(dāng)前類的反射,獲取到值,并對這些值進(jìn)行操作,通常是配置之類的,在框架中用得非常多(這是廢話)
元注解: 即對注解進(jìn)行注解的注解,主要以下幾個
- Target
定義一個注解時,規(guī)定這個注解可以作用在哪些范圍(類、方法、變量等) - Retention
定義注解的生命周期,通常使用Runtime
1.1元注解Target
源碼比較簡單,只有一個元素,是一個ElementType的數(shù)組
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target {ElementType[] value(); }ElementType是一個枚舉類,因此傳值的時候只能用ElementType.ANNOTATION_TYPE的方式
public enum ElementType {TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE,ANNOTATION_TYPE,PACKAGE,TYPE_PARAMETER,TYPE_USE }1.2元注解Retention
和Target差不多,也是只有一個元素,元素類型是一個枚舉
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Retention {RetentionPolicy value(); }public enum RetentionPolicy {SOURCE,CLASS,RUNTIME }2.自定義注解
2.1定義注解接口
聲明一個注解接口時默認(rèn)使用以下格式
interface前加@,默認(rèn)繼承java.lang.annotation
2.2定義注解元素
同樣有固定格式,如下
String method(); //無默認(rèn)值 String ip() default "localhost"; //設(shè)置默認(rèn)值為localhost只要注解中定義了元素,那么使用注解時就一定要給定義的元素賦值,有默認(rèn)值的可以不寫
2.3自定義實(shí)例
根據(jù)以上,自定義的一個注解如下
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface myAnnotation {String method();String ip() default "http://localhost:8080"; //設(shè)置默認(rèn)值為localhost }使用在實(shí)際方法中如下,先創(chuàng)建一個測試類,在方法上添加這個注解,這個實(shí)例定義了方法為post,ip沒有定義,使用默認(rèn)值
public class testMyAnno {@myAnnotation(method = "post")public void test(){System.out.println("測試一下注解");} }此處再加上一個testNg的test注解直接運(yùn)行,自定義的注解是不會產(chǎn)生任何作用的,運(yùn)行結(jié)果如下
因此還需要一個另外的啟動類,啟動類如下
public class work {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {Class c1 = Class.forName("anno.testMyAnno"); //根據(jù)全類名獲得class類Method test = c1.getMethod("test"); //根據(jù)方法名獲得test方法if(test.isAnnotationPresent(myAnnotation.class)){ //判斷test類上是否有myAnnotation修飾myAnnotation annotation = test.getAnnotation(myAnnotation.class); //有的話獲取這個注解對象String ip = annotation.ip(); //獲取注解中的ip值String method = annotation.method();if(method.toUpperCase().equals("POST")){HttpPost post = new HttpPost("ip");}System.out.println("ip:"+ip+",method:"+method);}CloseableHttpClient aDefault = HttpClients.createDefault();System.out.println("創(chuàng)建了httpclient以及post請求");test.invoke(c1.newInstance(),null); //調(diào)用test方法} }比較直觀的看出,先是獲得了方法以及方法上的注解內(nèi)容,根據(jù)注解內(nèi)容做處理,最后再調(diào)用注解內(nèi)容,大概是這樣的模式,執(zhí)行結(jié)果如下
2.4單值注解
最后的最后一個小的點(diǎn),即當(dāng)注解中只有一個元素,且元素的名稱為value時,在寫注解值時可以不把元素名value寫出來,如下
public @interface anno1 {String value(); }@anno1("123") public void test1(){}總結(jié)
- 上一篇: 为什么使用VO,DTO,BO
- 下一篇: EEG信号处理与分析常用工具包介绍【第2