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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值