java中自定義annotation
一 自定義注解的語法很簡單
public @interface MyAnnotation
{
}
上麵的代碼就定義了一個空注解,名字為MyAnnotation。
二 自定義注解也可以有屬性
public @interface MyAnnotation
{
public String key() default "name";
public String value() default "xy";
}
若要策略為運行時注解,需加上Retention注解
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
public String key() default "name";
public String value() default "xy";
}
三 為使Annotation有意義,必須結合反射取得設置的內容,下麵是一個完整的例子
MyAnnotation.java
package cn.interfaces;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
public String key() default "name";
public String value() default "xy";
}
SimpleBean.java
package cn.bean;
import cn.interfaces.MyAnnotation;
public class SimpleBean
{
@MyAnnotation(key = "name", value = "xy")
public void save()
{
System.out.println("save");
}
}
Test.java
package cn.test;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import cn.interfaces.MyAnnotation;
public class Test
{
public static void main(String[] args) throws IOException,
ClassNotFoundException, SecurityException, NoSuchMethodException
{
Class<?> c = Class.forName("cn.bean.SimpleBean");
Method saveMethod = c.getMethod("save");
Annotation an[] = saveMethod.getAnnotations(); // 取得全部的運行時Annotation
for (Annotation a : an)
{
System.out.println(a);
}
if (saveMethod.isAnnotationPresent(MyAnnotation.class)) // 該方法上是否存在該種類型的注解
{
MyAnnotation ma = saveMethod.getAnnotation(MyAnnotation.class);
String key = ma.key();
String value = ma.value();
System.out.println("key = " + key);
System.out.println("value = " + value);
}
}
}
輸出結果
@cn.interfaces.MyAnnotation(value=xy, key=name)
key = name
value = xy
結論
annotation和反射相結合會有很大的作用。
最後更新:2017-04-02 15:28:28
上一篇:
java中自定義annotation
下一篇:
oracle中兩表之間值互相插入和表自身插入值
ubuntu中安裝deb、bin、rpm、及源程序文件
SpringOne開發者大會技術資料下載地址
每秒百萬查詢:MySQL與PG在苛刻負載下的和平之戰
2011年騰訊校園之星互聯網應用開發大賽之我見
如何解決:Android中 Error generating final archive: Debug Certificate expired on 10/09/18 16:30 的錯誤
8月3日雲棲精選夜讀:LSF-SCNN:一種基於CNN的短文本表達模型及相似度計算的全新優化模型
ibatis中的模煳查詢
紮克伯格的政治野心:2017年他想走遍美國52個州
Maven學習八之pom.xml簡介以及客戶端下載包的流程
Stripes學習(一)