歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中自定義annotation

Java中自定義annotation

日期:2017/3/1 10:09:17   编辑:Linux編程

一 自定義注解的語法很簡單

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和反射相結合會有很大的作用。

Copyright © Linux教程網 All Rights Reserved