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-03 05:40:29
上一篇:
矩形的個數
下一篇:
Oracle中的substr方法
通過金礦模型介紹動態規劃
Linux內核中的內存管理淺談
iOS開發那些事--簡單表視圖
Android開源庫loopj的android-async-http的 JsonHttpResponseHandler 存在死循環GC_CONCURRENT
MySQL帶參數的存儲過程小例子
《理解專業程序員》-第四章:我們能更有效的思考嗎?
MSSQL · 架構分析 · 從SQL Server 2017發布看SQL Server架構的演變
從零到一:IOS平台TensorFlow入門及應用詳解(附源碼)(一)
MySQL 數據庫 備份與恢複
Win8觸控時代來了,該跟Windows XP說再見了