其实嘞,前面在玩aop的时候也有写过自定义注解来实现aop。今天就来系统学习一下注解。
一、定义注解
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注解,被称为元注解。这里要说说注解定义后的使用,下面写一个简单用例:
package org.ssm.king.annotationtest;
public class AnnotationTest {
@CustomAnnotation(id = 100, description = "userName must be true")
public boolean validateUserName(String userName) {
return userName.matches("");
}
}
看到这,我自己都想知道,注解的作用是什么呢?怎么感觉跟注释没什么两样啊!
二、注解处理器
与注解搭配使用,目的是为了让注解变得有用。这里会用到一些反射的东东。
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, AnnotationTest.class);
}
}
通过这个用例呢,就能看出,注解的其中一个用法。执行结果如下:
Found case:100 userName must be true
Warning : Missing use case - 101
Warning : Missing use case - 102
Process finished with exit code 0