首页 > 代码库 > java Annotation 自定义实例

java Annotation 自定义实例

Defining annotations

Here is the definition of the annotation above. You can see that annotation definitions look a lot like interface definitions. 

In fact, they compile to class files like any other Java interface:
-------------------------------首先定义注释,类似一个接口--------------------------------------------------------------------

import java.lang.annotation.*;
@Target(ElementType.METHOD) //此处成为元注解 ,注解的定义需要元注解
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {                                    //此处需要注意写法
public int id();
public String description() default "no description";
}

-------------------------------使用注释----------------------------------------------------------------------------------------------

import java.util.*;
public class PasswordUtils {
@UseCase(id = 47, description =
"Passwords must contain at least 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 passwords can’t equal previously used ones")
public boolean checkForNewPassword(
List<String> prevPasswords, String password) {
return !prevPasswords.contains(password);
}
}

-------------------------------使用反射机制,测试注解使用---------------------------------------------------------------------

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);
}

------------------------------------------------------------------输出结果----------------------------------------------------------------

/* Output:
Found Use Case:47 Passwords must contain at least one numeric
Found Use Case:48 no description
Found Use Case:49 New passwords can’t equal previously used ones
Warning: Missing use case-50