自定義註解會需要元註解,此處先介紹元註解。
元註解
java中有四種元註解:@Retention、@Inherited、@Documented、@Target
@Retention
註解的保留位置(枚舉RetentionPolicy),RetentionPolicy可選值:
- SOURCE:註解僅存在於源碼中,在class字節碼文件中不包含
- CLASS:默認的保留策略,註解在class字節碼文件中存在,但運行時無法獲得
- RUNTIME:註解在class字節碼文件中存在,在運行時可以通過反射獲取到
@Inherited
聲明子類可以繼承此註解,如果一個類A使用此註解,則類A的子類也繼承此註解
@Documented
聲明註解能夠被javadoc等識別(下面自定義註解處會有例子做介紹,點擊查看)
@Target
用來聲明註解範圍(枚舉ElementType),ElementType可選值:
- TYPE:接口、類、枚舉、註解
- FIELD:字段、枚舉的常量
- METHOD:方法
- PARAMETER:方法參數
- CONSTRUCTOR:構造函數
- LOCAL_VARIABLE:局部變量
- ANNOTATION_TYPE:註解
- PACKAGE:包
自定義註解介紹
自定義註解使用場景
- 類屬性自動賦值。
- 驗證對象屬性完整性。
- 代替配置文件功能,像spring基於註解的配置。
- 可以生成文檔,像java代碼註釋中的@see,@param等
1和2這個沒有做過類似實例,應該是像Hibernate中的使用註解映射Bean對象到數據庫一樣(此處爲個人猜測,如有錯誤請留言指出),中間有檢測和自動賦值。
自定義註解定義
定義一個自定義註解(不使用元註解):
public @interface Action{}
定義一個自定義註解(使用元註解,每個元註解都是可選,非必選):
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Target({ElementType.FIELD,ElementType.METHOD})
public @interface Action{
/**
* 操作類型
* @return
*/
//public String operateType() default "";
/**
* 方法描述
* @return
*/
public String description() default "no description";
/**
* 歸屬模塊
* @return
*/
public SysAuditModelType ownermodel() default SysAuditModelType.NULL ;
/**
* 日誌類型
* @return
*/
public String exectype() default "操作日誌";
/**
* 詳細信息
* @return
*/
public String detail() default "";
/**
* 執行順序
*/
public ActionExecOrder execOrder() default ActionExecOrder.AFTER;
}
註解中可以聲明成員方法,聲明的成員方法爲最終的註解裏面的參數,成員方法可以使用default關鍵字設置默認值。上面的註解使用如:
@Action(description="圖表導出word",execOrder=ActionExecOrder.AFTER,detail="圖表導出word<#if fl>成功<#else>失敗</#if>(W_QBD_FAL_PROBLEMRESET)")
自定義註解演示
新建一個自定義註解:
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Target({ElementType.FIELD,ElementType.METHOD})
@interface MyAnno{
public String name() default "zhangsan";
public String email() default "[email protected]";
}
定義一個User類,來使用自定義註解:
class User{
@MyAnno(name = "zhang")
private String name;
@MyAnno(name = "[email protected]")
private String email;
@MyAnno(name = "sayHelloWorld")
public String sayHello(){
return "";
}
}
- 通過反射獲取註解信息
下面我們通過反射來演示下獲取屬性的註解信息和方法的註解信息:
Method[] methods = User.class.getMethods();
//Field[] fields = User.class.getFields();
Field[] fields = User.class.getDeclaredFields();
/*
getFields:只能訪問public屬性及繼承到的public屬性
getDeclaredFields:只能訪問到本類的屬性,不能訪問繼承到的屬性
getMethods:只能訪問public方法及繼承到的public方法
getDeclaredMethods:只能訪問到本類的方法,不能訪問繼承到的方法
getConstructors:只能訪問public構造函數及繼承到的public構造函數
getDeclaredConstructors:只能訪問到本類的構造函數,不能訪問繼承到的構造函數
*/
for (Field field : fields) {
MyAnno annotation = field.getAnnotation(MyAnno.class);
if(annotation!=null){
System.out.println("property="+annotation.name());
}
}
for (Method method : methods) {
MyAnno annotation = method.getAnnotation(MyAnno.class);
if(annotation!=null){
System.out.println("sayHello="+annotation.name());
}
}
輸出如下:
property=zhang
[email protected]
sayHello=sayHelloWorld
原文:https://blog.csdn.net/bluuusea/article/details/79996572