轉(zhuǎn)載注明出處:http://www.itdecent.cn/p/898d5893cda5
1. 概述
Java在1.5版本引入注解Annotation,又稱Java標(biāo)注,注解是一種語法元數(shù)據(jù),可以被直接使用到源代碼中,類/方法/變量/參數(shù)/包名等都可以被注解。和Javadoc標(biāo)簽不同,編譯器在生成class文件時(shí)候能夠保留注解代碼,同時(shí),可能為了在程序運(yùn)行過程中(run-time)可以使用注解,Java虛擬機(jī)會(huì)把注解保留,這樣就可以通過反射獲取注解Annotation的相關(guān)信息。
2. 內(nèi)置注解
其實(shí)我們平時(shí)會(huì)經(jīng)常遇見注解,例如@Override、@Deprecated等等,這些都是JDK中內(nèi)置的注解,先來看看Java內(nèi)置的注解主要有哪些。
-
作用于Java代碼的注解
- @Override 檢查某個(gè)方法是否是復(fù)寫的方法,如果這個(gè)方法在父類或者實(shí)現(xiàn)的接口中未找到,編譯會(huì)出錯(cuò)。
- @Deprecated 標(biāo)記某個(gè)方法或者類被廢棄,如果使用該類或者方法,編譯過程會(huì)報(bào)警告
- @SuppressWarnings 通知編譯器忽略關(guān)于被標(biāo)注的參數(shù)的警告
- @SafeVarargs 忽略關(guān)于調(diào)用含有泛型參數(shù)的方法或者構(gòu)造器的警告,1.7新增注解
- @FunctionalInterface 表明某一個(gè)聲明的接口將被用作功能性接口,1.8新增注解
-
作于其他注解的注解,被稱為元注解(Meta Annotation)
- @Retention 指明被標(biāo)注的注解在什么時(shí)候使用(也就是注解什么時(shí)候會(huì)被保留)
- 僅僅在源代碼中保留,在編譯過程中丟棄(RetentionPolicy.SOURCE)
- 注解在編譯過程中保存到class文件,在class文件被加載時(shí)候忽略(RetentionPolicy.CLASS)
- 注解在class文件加載時(shí)候被讀取,也就是運(yùn)行中注解可用,可以通過反射獲取注解信息(RetentionPolicy.RUNTIME)
- @Documented 指明在生成Javadoc時(shí)候,被標(biāo)注的注解將被寫入Javadoc文檔中
- @Target 指明被標(biāo)注的注解的作用范圍
- ElementType.TYPE:用于描述類、接口(包括注解類型) 或enum聲明
- ElementType.FIELD:用于描述域
- ElementType.METHOD:用于描述方法
- ElementType.PARAMETER:用于描述參數(shù)
- ElementType.CONSTRUCTOR:用于描述構(gòu)造器
- ElementType.LOCAL_VARIABLE:用于描述局部變量
- ElementType.ANNOTATION_TYPE:用于描述注解
- ElementType.PACKAGE:用于描述包
- @Inherited 指明被標(biāo)注的注解是被繼承的,也就是說如果一個(gè)@Inherited修飾的annotation類型被用于一個(gè)類,則這個(gè)annotation也會(huì)作用于改類的子類。
- @Repeatable 指明被標(biāo)注的注解可以多次作用于同一個(gè)對(duì)象,1.9新增注解
- @Retention 指明被標(biāo)注的注解在什么時(shí)候使用(也就是注解什么時(shí)候會(huì)被保留)
3. 自定義注解
上面說了那么多注解,大家集中關(guān)注元注解,我們自定義注解時(shí)候,通常會(huì)使用元注解來協(xié)助我們。自定義注解格式為public @interface 注解名 {定義體},使用@interface自定義注解時(shí),自動(dòng)繼承了java.lang.annotation.Annotation接口。自定義注解時(shí),不能繼承其他的注解或接口。注解中聲明的方法實(shí)際上是聲明了一個(gè)注解參數(shù),方法的名稱就是參數(shù)的名稱,返回值類型就是參數(shù)的類型,可以通過default來聲明參數(shù)的默認(rèn)值。
自定義注解很簡單,使用@interface來定義一個(gè)注解,如下。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface ClassInfo {
String author() default "Wang";
String date();
String comments();
}
自定義了一個(gè)名為ClassInfo的注解,根據(jù)@Retention可以得知這個(gè)注解會(huì)一直存在,也就是在程序運(yùn)行中時(shí)候,這個(gè)注解還是有效的;@Target(ElementType.TYPE)說明ClassInfo注解的是作用于類、接口或enum聲明的;@Documented說明ClassInfo信息可以被寫入Javadoc文檔中。
再來看一下自定義注解中的一些注解參數(shù),里面有三個(gè)注解參數(shù),注解參數(shù)是可以設(shè)置默認(rèn)值,例如author注解參數(shù),默認(rèn)值為Wang,其他兩個(gè)參數(shù)就沒有默認(rèn)值。
再來看另一個(gè)自定義的注解。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MethodInfo {
String description() default "No Description";
String date();
}
這個(gè)自定義的注解MethodInfo是作用于方法的,在程序運(yùn)行中時(shí)候,這個(gè)注解也會(huì)存在;里面有兩個(gè)注解參數(shù)。
注解參數(shù)的定義(方法的定義),只能用public或者default兩個(gè)訪問權(quán)限修飾符,參數(shù)的類型支持以下幾種。
- 八種基本數(shù)據(jù)類型(byte,int,short,long,float,double,char,boolean)
- String類型
- Class類型
- enum類型
- Annotation類型
- 以上所有類型的數(shù)組
4. 注解的使用
除了上面兩個(gè)注解,又添加了一個(gè)Field作用域的注解。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldInfo {
String type();
String name();
}
自定義的注解中的注解參數(shù)如果沒有聲明默認(rèn)值,在使用自定義注解時(shí)候,必須給這些參數(shù)賦值,否則編譯器會(huì)報(bào)錯(cuò)。
看一下注解使用的代碼:
@ClassInfo(author = "wang",
date = "2016/9/13",
comments = "annotation demo")
public class AnnotationDemo {
@FieldInfo(type = "public", name = "firstField")
public int firstField;
@FieldInfo(type = "private", name = "secondField")
private String secondField;
@MethodInfo(description = "method in AnnotationDemo", name = "firstMethod")
public void firstMethod(String value) {
System.out.printf("first method involved");
}
@MethodInfo(description = "method in AnnotationDemo", name="secondMethod")
private void secondMethod() {
System.out.printf("first method involved");
}
}
3 5. 獲取注解信息
要獲取注解信息,首先得保證注解在程序運(yùn)行時(shí)候會(huì)存在,所以一般會(huì)給自定義的注解添加了@Retention(RetentionPolicy.RUNTIME)元注解,這樣在程序運(yùn)行過程中,我們可以通過反射去獲取一些注解信息,關(guān)于反射的說明,可以查看這篇文章。
public class AnnotationTest {
public static void main(String[] args) {
resolveClassAnnotationInfo(AnnotationDemo.class);
resolveFieldAnnotationInfo(AnnotationDemo.class);
resolveMethodAnnotationInfo(AnnotationDemo.class);
}
private static void resolveClassAnnotationInfo(Class<?> clz) {
// 判斷該類是否有ClassInfo注解
if(clz.isAnnotationPresent(ClassInfo.class)) {
ClassInfo classInfo = (ClassInfo) clz.getAnnotation(ClassInfo.class);
System.out.println(classInfo.author() + " " + classInfo.comments() + " " + classInfo.date());
}
}
private static void resolveFieldAnnotationInfo(Class<?> clz) {
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
if(field.isAnnotationPresent(FieldInfo.class)) {
FieldInfo fieldInfo = (FieldInfo) field.getAnnotation(FieldInfo.class);
System.out.println(fieldInfo.type() + " " + fieldInfo.name());
}
}
}
private static void resolveMethodAnnotationInfo(Class<?> clz) {
Method[] methods = clz.getDeclaredMethods();
for (Method method : methods) {
if(method.isAnnotationPresent(MethodInfo.class)) {
MethodInfo methodInfo = (MethodInfo) method.getAnnotation(MethodInfo.class);
System.out.println(methodInfo.name() + " " + methodInfo.description());
}
}
}
}
通過反射獲取類中的Field/Method等等,通過getAnnotation()或者getAnnotations()獲取相關(guān)注解,拿到具體注解就可以獲取具體的信息了。
運(yùn)行結(jié)果輸出如下:

6. 總結(jié)
對(duì)于Java的初學(xué)者甚至是有一定經(jīng)驗(yàn)的Java開發(fā)人員,對(duì)Java注解的接觸可能比較少,而在實(shí)際中,也很少用到注解,但是會(huì)經(jīng)常會(huì)在代碼里面看見,這篇文章算是對(duì)注解的淺顯介紹,最起碼在代碼層面是閱讀無壓力的。