题目要求
自定义注解,该注解用来描述,方法运行所需的时间上限(用long类型的数据表示时间,单位为ms),
然后,自定义注解处理器,运行加了运行时间上限注解的方法,判断方法的运行时间,
是否超出了注解中规定的时间上限,如果超过,则返回true,未超过返回false
实现代码
第一步:定义注解
package homework;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/*自定义注解,该注解用来描述,方法运行所需的时间上限(用long类型的数据表示时间,单位为ms)*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RunTime {
long maxRunTimeMillis();
}
第二步:定义目标类,以及目标类的run方法。注解作用在该类的run方法上。
目标类还包含main方法,用来测试注解处理器
package homework;
import java.lang.reflect.InvocationTargetException;
/*定义一个类,注解作用在该类的run方法上,run方法使用Thread.sleep()方法,控制运行时间*/
public class Work1 {
public Work1(){}
@RunTime(maxRunTimeMillis = 200)
public void run() throws InterruptedException {
Thread.sleep(300);
}
public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, InterruptedException, IllegalAccessException {
AnnotationProcess process = new AnnotationProcess();
System.out.println("运行run方法,运行时间是否满足约束条件:200ms\n" + process.runTimeIllegal());
}
}
第三步:定义一个注解处理器,实现的详细过程请看代码
package homework;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*然后,自定义注解处理器,运行加了运行时间上限注解的方法,判断方法的运行时间,
是否超出了注解中规定的时间上限,如果超过,则返回true,未超过返回false*/
public class AnnotationProcess {
//处理器使用反射技术实现,反射技术的起点是Class。
Class workClz;
public AnnotationProcess() throws ClassNotFoundException {
this.workClz = Class.forName("homework.Work1");
}
//此方法,返回目标类的运行时间是否满足约束。如果满足,返回true,不满足,返回false
public boolean runTimeIllegal() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, InterruptedException {
//利用反射获取目标类的run方法,并破解权限
Method method = workClz.getDeclaredMethod("run");
method.setAccessible(true);
//利用反射技术,获取目标类的run方法的注解,以及注解信息。
if(method.isAnnotationPresent(RunTime.class)){
Annotation annotation = method.getAnnotation(RunTime.class);
long maxRunTimeMillis = ((RunTime)annotation).maxRunTimeMillis();
//运行run方法,并记录他的运行时间
Constructor constructor = workClz.getDeclaredConstructor();
Work1 work1 = (Work1) constructor.newInstance();
long startTime = System.currentTimeMillis();
method.invoke(work1);
long endTime = System.currentTimeMillis();
long time = endTime - startTime;
//判断实际运行时间,是否满足约束条件
if(time > maxRunTimeMillis){
return false;
}
}
return true;
}
}