1、JDK自带的三种annotation
Documented @Retention(value=RUNTIME) public @interface Deprecated
public @interface Override
public @interface SuppressWarnings
影响范围:
Deprecated:RUNTIME,可以通过反射机制取出此annotation
Override:SOURCE,只存在于源代码中,编译之后则不存在,无法通过反射获取
SuppressWarnings:SOURCE,只存在于源代码中,编译之后则不存在,无法通过反射获取
2、自定义annotation
(1)自定义annotation
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- @Retention(value=RetentionPolicy.RUNTIME)
- public @interface MyAnnotation {
- public String val1() default "hello world";
- public String val2();//必须赋值
- public int[] val3();//必须赋值
- public String[] val4() default { "zhansan", "lisi" };
- public MyEnum val5() default MyEnum.ZHANGSAN; //annotation的值限定于枚举中的值
- }
- enum MyEnum{
- ZHANGSAN,
- LISI,
- WANGWU
- }
(2)使用annotation
- @Deprecated
- public class Demo02 {
- @Deprecated
- @SuppressWarnings("unchecked")
- @MyAnnotation(val2 = "", val3 = { 0 })
- public String getValue() {
- return "zhansgan";
- }
- @MyAnnotation(val2 = "lisi", val3 = { 1, 2, 3 })
- public int divide(int a, int b) {
- return a / b;
- }
- }
(3)使annotation产生作用
【注意】只能取得保持策略为RUNTIME的annotation,其他范围的由于不是运行时存在,所以反射的时候无法获取
- import java.lang.annotation.Annotation;
- import java.lang.reflect.Method;
- public class Demo02Reflect {
- public static void main(String[] args) throws Exception {
- Class clazz = Class.forName("com.alibaba.designpattern.anno.Demo02");
- Annotation[] annos = clazz.getDeclaredAnnotations();
- for (Annotation anno : annos) {
- System.out.println(clazz.getName() + "类 anno: " + anno);
- }
- System.out.println("------------------------");
- Method[] methods = clazz.getMethods();
- for(Method method : methods){
- Annotation[] methodAnnos = method.getAnnotations();
- for(Annotation methodAnno : methodAnnos){
- System.out.println(method.getName() + "方法 anno: " + methodAnno);
- }
- }
- }
- }
运行结果:
- com.alibaba.designpattern.anno.Demo02类 anno: @java.lang.Deprecated()
- ------------------------
- getValue方法 anno: @java.lang.Deprecated()
- getValue方法 anno: @com.alibaba.designpattern.anno.MyAnnotation(val4=[zhansan, lisi], val1=hello world, val5=ZHANGSAN, val2=, val3=[0])
- divide方法 anno: @com.alibaba.designpattern.anno.MyAnnotation(val4=[zhansan, lisi], val1=hello world, val5=ZHANGSAN, val2=lisi, val3=[1, 2, 3])
同时可以通过获取annotation中的参数进行操作。
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/534694,如需转载请自行联系原作者