一、编程注解处理器。
在JavaSE5中扩展了反射机制的API,这样可以有效读取定义的注解。例子如下:读取PasswordUtils类中方法的注解。
package org.wangkeqing.annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class UseCaseTracker {
public static void main(String[] args) {
List<Integer> useCases = new ArrayList<Integer>();
Collections.addAll(useCases, 47,48,49,50,51);
trackUseCases(useCases,PasswordUtils.class);
}
//使用反射机制读取Annotation注解
public static void trackUseCases(List<Integer> useCases,Class<?> clz){
for(Method m:clz.getDeclaredMethods()){
//获取UseCase的annotation
UseCase uc = m.getAnnotation(UseCase.class);
if(uc!=null){
System.out.println("found UseCase:"+uc.id()+"----"+uc.description());
//找到Annotation后,把useCases中相应的id数据删掉(剩下没有annotation的id值)
useCases.remove(new Integer(uc.id()));
}
}
//遍历useCases中剩下的id数据
for(int i:useCases){
System.out.println("Warning :Missing use case-"+i);
}
}
}
程序中使用了反射机制中的两个方法:getAnnotation()和getDeclaredMethods()方法。他们都属于AnnotatedElemment接口,Class,Method,Field都实现了该接口。getAnnotation()返回注解对象,如果该方法没有注解,返回null值。通过调用id()和description()方法可以从返回的UseCase注解对象中获取到id和description的值。 其中encriptPassword方法在注解的时候没有description的值,它的值就是默认值。
二、注解元素类型
在上例中,标签@UseCase由UseCase.java定义,其中包含一个int类型id,String类型的description。注解元素可以使用的类型如下。
(1)、所有的基本类型(boolean,byte,char,short,int,long,float,double)
(2)、String
(3)、Class
(4)、enum
(5)、Annotation
(6)、以上类型的数组
注意:不能使用其他类型,否则编译器会报错。