查看代碼的時(shí)候發(fā)現(xiàn)了一個(gè)annotation類型的文件,好奇百度了一下,又有新技能get。以前我了解的java注解,就是用//等符號(hào)標(biāo)注的注釋,或者@author,再或者,就是最近接觸的testng框架注釋。
今天看到的代碼如下:
package com.api.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR})
public @interface DBUnitScript {
public String value();
public String dataSourceName();
}
文件類型為annotation,即注解。這是一個(gè)自定義的注解(Annotation)類,即DBUnitScript, 在定義注解(Annotation)類時(shí)使用了另一個(gè)注解類Retention。
*在注解類上使用另一個(gè)注解類,那么被使用的注解類就稱為元注解。
新建注解類
新建一個(gè)class,在kind中選擇annotation類型文件,即可新建一個(gè)注解類。
以下部分內(nèi)容摘抄自孤傲蒼狼,侵刪。原帖地址:http://www.cnblogs.com/xdp-gacl/p/3622275.html
注解就相當(dāng)于一個(gè)你的源程序要調(diào)用一個(gè)類,在源程序中應(yīng)用某個(gè)注解,得事先準(zhǔn)備好這個(gè)注解類。就像你要調(diào)用某個(gè)類,得事先開發(fā)好這個(gè)類。
java中元注解有四個(gè): @Retention @Target @Document @Inherited
1、Retention注解決定注解的生命周期
1、@Retention()
這里是在注解類DBUnitScript上使用另一個(gè)注解類即Retention注解,這里的Retention稱為元注解。
2、@Retention(RetentionPolicy.SOURCE)
這個(gè)注解的意思是讓DBUnitScript注解只在java源文件中存在,編譯成.class文件后注解就不存在了
3、@Retention(RetentionPolicy.CLASS)
這個(gè)注解的意思是讓DBUnitScript注解在java源文件(.java文件)中存在,編譯成.class文件后注解也還存在,
4、 @Retention(RetentionPolicy.RUNTIME)
意思是讓DBUnitScript這個(gè)注解的生命周期一直程序運(yùn)行時(shí)都存在
5、被DBUnitScript注解類標(biāo)識(shí)的類被類加載器加載到內(nèi)存中后MyAnnotation注解就不存在了
@Retention元注解的講解:其三種取值:RetentionPolicy.SOURCE、RetentionPolicy.CLASS、RetentionPolicy.RUNTIME分別對(duì)應(yīng):Java源文件(.java文件)---->.class文件---->內(nèi)存中的字節(jié)碼
2、Target注解
Target注解決定注解可以加在哪些成分上,如加在類身上,或者屬性身上,或者方法身上等成分,@Target默認(rèn)值為任何元素(成分)
如:
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR})
@Target:注解的作用目標(biāo)
@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) ///包
3、@Document:說明該注解將被包含在javadoc中
4、 @Inherited:說明子類可以繼承父類中的該注解
為注解添加屬性
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.CONSTRUCTOR})
public @interface DBUnitScript {
//屬性
public String value();//數(shù)據(jù)腳本地址
public String dataSourceName();
}
把自定義的注解類加到某個(gè)類上
@ DBUnitScript
public class AnnotationUse{
}
應(yīng)用屬性
@DBUnitScript(value = "sql/addCustomAccountTitles.sql", dataSourceName = "dataSource")
//在執(zhí)行方法前先調(diào)用DBUnitScript注解
public void testCustomerAccountTitles(SelectItem[] cols, Object[] data) throws Exception{
String api = "";//請(qǐng)求api
Map<String, String> params = new HashMap<>();
params.put("pId", data[2].toString());
Response response = request(api, HttpMethod.POST, params);
}