示例出自《java编程思想》
自定义注解:
package demo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
public int id();
public String description() default "no description";
}
注解处理器:
package demo;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//注解处理器 使用反射机制查找@UseCase标记
public class UseCaseTracker {
public static void trackUseCases(List<Integer> useCases, Class<?> cl){
for(Method m: cl.getDeclaredMethods()){
UseCase uc = m.getAnnotation(UseCase.class);
if(uc != null){
System.out.println("Found Use Case:" + uc.id() + " " + uc.description());
useCases.remove(new Integer(uc.id()));
}
}
for(int i: useCases){
System.out.println("Warning: Missing use case-" + i);
}
}
public static void main(String[] args) {
List<Integer> useCases = new ArrayList<>();
Collections.addAll(useCases, 47,48,49,50);
trackUseCases(useCases, PasswordUtils.class);
}
}
// 输出结果:
// Found Use Case:49 password muset contain at least one numeric
// Found Use Case:47 password muset contain at least one numeric
// Found Use Case:48 password muset contain at least one numeric
// Warning: Missing use case-50
注解示例:
package demo;
public class PasswordUtils {
@UseCase(id=47, description="password muset contain at least one numeric")
public boolean validatePassword(String password){
return (password.matches("\w*\d\w*"));
}
@UseCase(id=48, description="password muset contain at least one numeric")
public boolean encryptPassword(String password){
return (password.matches("\w*\d\w*"));
}
@UseCase(id=49, description="password muset contain at least one numeric")
public boolean checkForNewPassword(String password){
return (password.matches("\w*\d\w*"));
}
}