如下自定义注解
@Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Target({ElementType.METHOD}) public @interface TestAnnotation { Class<? extends CommonCheck>[] commonChecks(); }
这是一个作用域在方法上的注解,注解内部包含一个 Class<? extends CommonCheck>[]通配泛型数组,表示CommonCheck的一个未知子类数组
CommonCheck接口:
public interface CommonCheck { public boolean check(); }
CommonCheck接口的两个实现类:
@Slf4j public class ClassCheck implements CommonCheck { @Override public boolean check() { log.info("my name is ClassCheck"); return false; } }
@Slf4j public class TokenCheck implements CommonCheck { @Override public boolean check() { log.info("my name is TokenCheck"); return false; } }
测试类:
public class TestAnnotationService { @TestAnnotation(commonChecks = {ClassCheck.class,ClassCheck.class}) public static void getClassCheck(){ } @TestAnnotation(commonChecks= {ClassCheck.class,TokenCheck.class}) public static void getTest(){ } public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException { Method[] methods=TestAnnotationService.class.getMethods(); for(int i=0;i<methods.length;i++){ if(methods[i].isAnnotationPresent(TestAnnotation.class)){ TestAnnotation testAnnotation=methods[i].getAnnotation(TestAnnotation.class); List<Class<? extends CommonCheck>> checkList=new ArrayList<>(); for(int c=0;c<testAnnotation.commonChecks().length;c++){ checkList.add(testAnnotation.commonChecks()[c]); } for(Class<? extends CommonCheck> myCheck:checkList) { myCheck.getMethod("check", null).invoke(myCheck.newInstance(), null); } } } } }
在测试类中,我们可以看到通过反射的方式获取到了每个方法上的注解 TestAnnotation,遍历每个
TestAnnotation中的commonChecks属性,然后通过反射的方式拿到每个子类的check方法,反射运行这个方法
完成通过注解的形式对方法层面非倾入式约束。