Java Annotation学习

1. 定义自己的Annotation类型

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented //开发人员定制Javadoc 不支持的文档属性 ,既然不是文档支持的,就需要设置@Retention(RetentionPolicy.RUNTIME)将其保留到运行时
@Retention(RetentionPolicy.RUNTIME) //注释保留时间,具体看API中有说明
@Target({ElementType.FIELD}) //注释应用目标,ElementType枚举是自带的集中类型,具体在API中有说明
public @interface Serializer {
boolean needSerialize();
int length();
String name();
}

2. 将自定义的注释添加到相应的Target上

import java.awt.Color;

public class Robin {
@Serializer(needSerialize=false,length=14,name="ColorField")
private Color color;
@Serializer(needSerialize=true,length=20,name="NameField")
private String Name;
}

 

3. 测试一下

import java.lang.reflect.Field;

public class Process {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Class<Robin> temp = getRobin();
try {
Robin robin = temp.newInstance();
Field[] fields = temp.getDeclaredFields();
for(Field item : fields){
Serializer annotation = item.getAnnotation(Serializer.class);
System.out.println(annotation.length()+" "+annotation.name());
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static Class<Robin> getRobin()
{
return Robin.class;
}
}

posted @ 2013-04-10 11:28  AngelGong  阅读(101)  评论(0编辑  收藏  举报