Java在1.5開始引入了注解,目前流行的框架都在用注解,可想而知注解的強(qiáng)大之處。
以下通過自定義注解來深入了解java注解。
一、創(chuàng)建自定義注解
package com.sam.annotation;
import java.lang.annotation.*;
/**
* @author sam
* @since 2017/7/13
*/
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyMessage {
String name() default "sam";
int num() default 0;
String desc();
}
說明:
@Target、@Retention、@Inherited、@Documented為元注解(meta-annotation),它們是負(fù)責(zé)注解其他注解的。
- Target:指明注解支持的使用范圍,取值可以參考枚舉ElementType,以下:
- ElementType.TYPE //類、接口、枚舉
- ElementType.FIELD //屬性
- ElementType.METHOD //方法
- ElementType.PARAMETER //參數(shù)
- ElementType.CONSTRUCTOR //構(gòu)造器
- ElementType.LOCAL_VARIABLE //局部變量
- ElementType.ANNOTATION_TYPE //注解
- ElementType.PACKAGE //包
- Retention:指明注解保留的的時(shí)間長短,取值參考枚舉RetentionPolicy,一下:
- SOURCE //源文件中保留
- CLASS //class編譯時(shí)保留
- RUNTIME //運(yùn)行時(shí)保留
- Inherited:指明該注解類型被自動(dòng)繼承。如果一個(gè)annotation注解被@Inherited修飾,那么該注解作用于的類 的子類也會(huì)使用該annotation注解。
- Documented:指明擁有這個(gè)注解的元素可以被javadoc此類的工具文檔化。
二、創(chuàng)建測(cè)試類,使用自定義注解
package com.sam.annotation;
/**
* @author sam
* @since 2017/7/13
*/
public class AnnotationTest {
@MyMessage(num = 10, desc = "參數(shù)a")
private static int a;
@MyMessage(name = "Sam test", desc = "測(cè)試方法test")
public void test() {
System.out.println("test");
}
}
在該類中的屬性和方法,使用了自定義的注解,并指明了參數(shù)。
那么現(xiàn)在就需要解析自定義的注解。
三、解析注解
使用反射機(jī)制處理自定義注解
package com.sam.annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 使用反射處理注解
*
* @author sam
* @since 2017/7/13
*/
public class MyMessageProcessor {
public static void main(String[] args) {
try {
//加載annotationTest.class類
Class clazz = MyMessageProcessor.class.getClassLoader().loadClass("com.sam.annotation.AnnotationTest");
//獲取屬性
Field[] fields = clazz.getDeclaredFields();
//遍歷屬性
for (Field field : fields) {
MyMessage myMessage = field.getAnnotation(MyMessage.class);
System.out.println("name:" + myMessage.name() + " num:" + myMessage.num() + " desc:" + myMessage.desc());
}
//獲取類中的方法
Method[] methods = clazz.getMethods();
//遍歷方法
for (Method method : methods) {
//判斷方法是否帶有MyMessage注解
if (method.isAnnotationPresent(MyMessage.class)) {
// 獲取所有注解 method.getDeclaredAnnotations();
// 獲取MyMessage注解
MyMessage myMessage = method.getAnnotation(MyMessage.class);
System.out.println("name:" + myMessage.name() + " num:" + myMessage.num() + " desc:" + myMessage.desc());
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
運(yùn)行MyMessageProcessor 得到結(jié)果:
name:sam num:10 desc:參數(shù)a
name:Sam test num:0 desc:測(cè)試方法test
Process finished with exit code 0
具體定制注解所實(shí)現(xiàn)的內(nèi)容,可以在MyMessageProcessor.java中進(jìn)行修改。
自此,已經(jīng)對(duì)java的自定義注解有簡單的了解。
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。