结合反射+注解的注解处理器编程

练习:
自定义注解,该注解用来描述,方法运行所需的时间上限(用long类型的数据表示时间,单位为ms),
然后,自定义注解处理器,运行加了运行时间上限注解的方法,判断方法的运行时间,
是否超出了注解中规定的时间上限,如果超过,则返回true,未超过返回false

package com.homework.homework0808;

import java.util.concurrent.TimeoutException;

/**
 * @Author jinman1012@qq.com   2020/8/8 15:06
 * @Version 1.0
 *                               测试类
 */
public class Test {
    public static void main(String[] args) throws NoSuchMethodException, InterruptedException, TimeoutException {
        new TestRunTimeMethod().outputRunningTime(100);
    }
}
package com.homework.homework0808;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.TimeoutException;

/**
 * @Author jinman1012@qq.com   2020/8/8 14:27
 * @Version 1.0
 */
public class TestRunTimeMethod {
	//设置方法超时时间注解
    @RunTimeConstraint(runTime = 200)
    public void outputRunningTime(long sleepTime) throws InterruptedException, NoSuchMethodException, TimeoutException {
    	//获取系统当前时间 单位ms
        long startTime = System.currentTimeMillis();
        //使用线程休眠 模拟方法运行时间
        Thread.sleep(sleepTime);
        //获取系统当前时间 单位ms
        long endTime = System.currentTimeMillis();
        //调用注解处理器方法
        if(TimeDiffJudge.judgeTimeOut(endTime - startTime)) {
            System.out.println("==超时==");
        }else {
            System.out.println("==未超时==");
        }
    }
}

package com.homework.homework0808;

import java.lang.reflect.Method;
import java.util.concurrent.TimeoutException;

/**
 * @Author jinman1012@qq.com   2020/8/8 14:40
 * @Version 1.0
 */
public class TimeDiffJudge {

    public static boolean judgeTimeOut(long timeDifferent) throws NoSuchMethodException, TimeoutException {
    	//获取类对象
        Class trmc = TestRunTimeMethod.class;
        //通过反射 获取注解的方法的方法对象
        Method ort = trmc.getDeclaredMethod("outputRunningTime",long.class);
        //绕过JVM权限检测
        ort.setAccessible(true);
        //判断方法对象是否有RunTimeConstraint注解
        if(ort.isAnnotationPresent(RunTimeConstraint.class)){
        	//获取注解对象及其值
            RunTimeConstraint annotation = ort.getAnnotation(RunTimeConstraint.class);
            long timeDiffConstraint = annotation.runTime();
            //判断方法运行时间与注解时间结果是否超时
            if(timeDifferent > timeDiffConstraint) {
//                throw new TimeoutException("程序运行时间超时 参数:" + timeDifferent+">" + timeDiffConstraint);
                return true;
            }
        }
        return false;
    }
}

package com.homework.homework0808;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RunTimeConstraint {
    long runTime();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值