Java中自定义annotation

2014-11-24 10:14:49 · 作者: · 浏览: 1

一 自定义注解的语法很简单


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