1:定義注解
package chapter20.one; 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(); //注解元素 為 id public String description() default "no description"; //設置默認值, }
2:使用注解:
package chapter20.one; import java.util.List; public class PasswordUtils { //使用的注解內容看將會被注解處理器,取出並解析。spring中寫不同的注解內容(提前定義好的),將會對應不同的處理結果 @UseCase(id=47,description="passwords must contain at least one numberic") public boolean validatePassword(String password){ return (password.matches("\\w*\\d\\w*")); } @UseCase(id=48) public String encryptPassword(String password){ return new StringBuilder(password).reverse().toString(); } @UseCase(id=49,description="New passwords can't equal pre viously used ones") public boolean chenkForNewPassword(List<String> prePasswords,String password){ return !prePasswords.contains(password); } }
3:編寫注解處理器
package chapter20.one; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 注解處理器 * @author admin * */ public class UseCaseTracker { public static void trackUseCases(List<Integer> useCases,Class<?> cl){ for(Method m:cl.getDeclaredMethods()){ UseCase uc=m.getAnnotation(UseCase.class); //根據PasswordUtils中的方法,獲取注解對象UseCase if(uc!=null){ System.out.println("found use case"+uc.id());//獲取相應的注解內容 } 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<Integer>(); Collections.addAll(useCases, 47,48,49,50); trackUseCases(useCases, PasswordUtils.class); } }
4:測試結果
found use case49
found use case47
found use case48
Warning :Missing use case -50
5:講解
java中元注解有四個: @Retention @Target @Document @Inherited;
@Retention:注解的保留位置
@Retention(RetentionPolicy.SOURCE) //注解僅存在於源碼中,在class字節碼文件中不包含
@Retention(RetentionPolicy.CLASS) // 默認的保留策略,注解會在class字節碼文件中存在,但運行時無法獲得,
@Retention(RetentionPolicy.RUNTIME) // 注解會在class字節碼文件中存在,在運行時可以通過反射獲取到
@Target:注解的作用目標
@Target(ElementType.TYPE) //接口、類、枚舉、注解
@Target(ElementType.FIELD) //字段、枚舉的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法參數
@Target(ElementType.CONSTRUCTOR) //構造函數
@Target(ElementType.LOCAL_VARIABLE)//局部變量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包
@Document:說明該注解將被包含在javadoc中
@Inherited:說明子類可以繼承父類中的該注解