標籤:ext main utils height declare collect stat img on()
註解(也被稱為中繼資料)為我們在代碼中添加資訊提供了一種形式化的方法,使我們可以在稍後某個時刻非常方便地使用這些資料。
--------------------------------------------------------------------------------------------------------------------------------------------
1.定義註解:
[java] view plain copy
- package com.test;
-
- 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";
- }
2.在下面的類中,有三個方法被註解為用例:
[java] view plain copy
- package com.test;
-
- import java.util.List;
-
- public class PasswordUtils {
- @UseCase(id = 47, description = "Passwords must contain at lease one numeric")
- 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 password can‘t equal previously used ones")
- public boolean checkForNewPassword(List<String> prevPasswords, String password) {
- return !prevPasswords.contains(password);
- }
- }
3.編寫註解處理器:
[java] view plain copy
- package com.test;
-
- import java.lang.reflect.*;
- import java.util.*;
-
- 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<Integer>();
- Collections.addAll(useCases, 47, 48, 49, 50);
- trackUseCases(useCases, PasswordUtils.class);
- }
- }
輸出:
Found Use Case:49 New password can‘t equal previously used ones
Found Use Case:47 Passwords must contain at lease one numeric
Found Use Case:48 no description
Warning: Missing use case-50
-
頂
-
1
Java註解@interface (入門)(轉)