java Annotation 自定义实例

2020-11-23 08:57

阅读:617

标签:des   style   java   color   使用   os   

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 prevPasswords, String password) {
return !prevPasswords.contains(password);
}
}

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

import java.lang.reflect.*;
import java.util.*;
public class UseCaseTracker {
public static void
trackUseCases(List 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 useCases = new ArrayList();
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

java Annotation 自定义实例,搜素材,soscw.com

java Annotation 自定义实例

标签:des   style   java   color   使用   os   

原文地址:http://blog.csdn.net/michael10001/article/details/24600441


评论


亲,登录后才可以留言!