码迷,mamicode.com
首页 > 编程语言 > 详细

java Annotation 自定义实例

时间:2014-04-27 21:47:05      阅读:348      评论:0      收藏:0      [点我收藏+]

标签: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<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

java Annotation 自定义实例,码迷,mamicode.com

java Annotation 自定义实例

标签:des   style   java   color   使用   os   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!