自定义注解Demo

来源:互联网 发布:淘宝直通车怎么关闭 编辑:程序博客网 时间:2024/06/05 08:46

1.自定义注解UseCase

package 注解;import static java.lang.annotation.ElementType.*;import java.lang.annotation.Retention;import static java.lang.annotation.RetentionPolicy.*;import java.lang.annotation.Target;@Target(value={METHOD})//注解信息保留到运行时@Retention(RUNTIME)public @interface UseCase {public String hehe();public int id();public String description() default "no description";}

2.在示例类中使用自定义注解

package 注解;import java.util.List;public class PswUtils {@UseCase(id=47,description="pwd must contain at least one number", hehe = "1")public boolean validPwd(String pwd){return (pwd.matches("\\w*\\d\\w*"));}@UseCase(id=48, hehe = "2")public String encryptPassword(String pwd){return new StringBuilder(pwd).reverse().toString();}@UseCase(id=49,description="new pwd can't contain ...", hehe = "3")public boolean checkForNewpwd(List<String> prePwd,String pwd){return !prePwd.contains(pwd);}}
3.编写注解处理器

package 注解处理器;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Collections;import java.util.List;import 注解.PswUtils;import 注解.UseCase;public class UseCaseTracker {public static voidtrackUseCases(List<?> useCases,Class<?> cl){for(Method m:cl.getDeclaredMethods()){UseCase uc = m.getAnnotation(UseCase.class);if(uc!=null){System.out.println("Found Use Case: id="+uc.id()+" annotion="+uc.description());useCases.remove(new Integer(uc.id()));useCases.remove(uc.hehe());}}for(Object i:useCases){System.out.println("Warning:minssing the case = "+i);}}//main()方法public static void main(String[] args) {List<Integer> useCases = new ArrayList<Integer>();Collections.addAll(useCases, 47,48,49,50);trackUseCases(useCases, PswUtils.class);System.out.println("##################");List<String> uc = new ArrayList<String>();Collections.addAll(uc, "1","2","3","4");trackUseCases(uc, PswUtils.class);}}

4.输出结果

Found Use Case: id=47 annotion=pwd must contain at least one numberFound Use Case: id=48 annotion=no descriptionFound Use Case: id=49 annotion=new pwd can't contain ...Warning:minssing the case = 50##################Found Use Case: id=47 annotion=pwd must contain at least one numberFound Use Case: id=48 annotion=no descriptionFound Use Case: id=49 annotion=new pwd can't contain ...Warning:minssing the case = 4