其实嘞,前面在玩aop的时候也有写过自定义注解来实现aop。今天就来系统学习一下注解。java
1、定义注解学习
package org.ssm.king.test; import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CustomAnnotation { int id(); String description() default "no description!"; }
这是一个简单自定义注解的定义。三种注解在以前有过讲解,在这就再也不赘述,特别说一下,这三种注解再加上@Inherited注解,被称为元注解。这里要说说注解定义后的使用,下面写一个简单用例:code
package org.ssm.king.annotationtest; public class AnnotationTest { @CustomAnnotation(id = 100, description = "userName must be true") public boolean validateUserName(String userName) { return userName.matches(""); } }
看到这,我本身都想知道,注解的做用是什么呢?怎么感受跟注释没什么两样啊!ip
2、注解处理器rem
与注解搭配使用,目的是为了让注解变得有用。这里会用到一些反射的东东。get
package org.ssm.king.annotationtest; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class UseCaseTracker { public static void trackUseCase(List<Integer> useCase, Class<?> cl) { for (Method m : cl.getDeclaredMethods()) { CustomAnnotation customAnnotation = m.getAnnotation(CustomAnnotation.class); if (customAnnotation != null) { System.out.println("Found case:" + customAnnotation.id() + " " + customAnnotation.description()); useCase.remove(new Integer(customAnnotation.id())); } } for (int i : useCase) { System.out.println("Warning : Missing use case - " + i); } } public static void main(String[] args) { List<Integer> userCase = new ArrayList<>(); Collections.addAll(userCase, 100, 101, 102); trackUseCase(userCase, AnnotationUtils.class); } }
经过这个用例呢,就能看出,注解的其中一个用法。执行结果以下:it
Found case:100 userName must be true Warning : Missing use case - 101 Warning : Missing use case - 102 Process finished with exit code 0