自定义注解使用案例

使用注解:
1、获取注解定义的位置对象 (Class,Method,Field)
2、获取指定的注解 getAnnotation(Class)
3、调用注解中的抽象方法

自定义Check注解:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {
}

Calculator类中只有method方法没有加@Check注解:

public class Calculator {

    @Check
    public void add() {
        System.out.println("1 + 0 =" + (1 + 0));
    }
    @Check
    public void sub() {
        System.out.println("1 - 0 =" + (1 - 0));
    }
    @Check
    public void mul() {
        System.out.println("1 * 0 =" + (1 * 0));
    }
    @Check
    public void div() {
        System.out.println("1 / 0 =" + (1 / 0));
    }

    public void method(){
        System.out.println("我是method方法.....");
    }
}

main测试:

public class MyAnnotationTest {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        //获取Calculator字节码文件对象
        Class<? extends Calculator> aClass = calculator.getClass();
        //获取文件中所有方法
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            //如果方法上有@Check注解,则执行该方法
            if (method.isAnnotationPresent(Check.class)) {
                try {
                    method.invoke(calculator);
                } catch (Exception e) {
                    System.out.println("出现异常的方法名:" + method.getName());
                    System.out.println("异常出现的原因:" + e.getCause().getMessage());
                }
            }
        }
    }
}

控制台信息:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值