JAVA注解 三 通过反射获取方法上的注解

如下自定义注解

@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方法,反射运行这个方法

完成通过注解的形式对方法层面非倾入式约束。

 

 


                
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值