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学习(一)