练习:
自定义注解,该注解用来描述,方法运行所需的时间上限(用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();
}