您的位置:首页 > 大数据 > 人工智能

Annotaion基础

2011-04-03 23:53 18 查看
1、JDK自带的三种annotation

Documented @Retention(value=RUNTIME) public @interface Deprecated

@Target(value=METHOD) @Retention(value=SOURCE) public @interface Override

[code]@Target(value={TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE}) @Retention(value=SOURCE) public @interface SuppressWarnings

[/code]
影响范围:

Deprecated:RUNTIME,可以通过反射机制取出此annotation

Override:SOURCE,只存在于源代码中,编译之后则不存在,无法通过反射获取  SuppressWarnings:SOURCE[b],只存在于源代码中,编译之后则不存在,无法通过反射获取[/b]


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中的参数进行操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  职场 休闲 annotation