注解练习(2.27)

文章目录

题目

1. 自定义注解,该注解用来描述,方法运行所需的时间上限(long类型的数据表示时间,单位为ms),

然后,自定义注解处理器,
运行          加了运行时间上限注解的方法,判断          方法的运行时间,是否超出了注解中规定的时间上限,
如果超过,则返回true,未超过返回false

结果

在这里插入图片描述

在这里插入图片描述

代码

package src;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @AUTHOR ZHANG
 * @data 2021/2/27 14:56
 */

//Step1-自定义注解,该注解用来描述,方法运行所需的时间上限(用long类型的数据表示时间,单位为ms)
//元注解
@Retention(RetentionPolicy.RUNTIME)
@Target({
    
    ElementType.METHOD})
@interface MethodRuntimeLimit {
    
    
    //注解的属性的数据类型:基本数据类型long
    long timeLimit();
}


//Step2-加了运行时间上限注解的方法(在类中)
class Person {
    
    
    //方法上添加注解,描述方法允许的运行时间上限
    @MethodRuntimeLimit(timeLimit = 100)
    public void method() {
    
    
        try {
    
    
            Thread.sleep(100);
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
    }
}

//Step-3 然后,自定义注解处理器
class PersonFactory {
    
    
    static Class Cls = Person.class;

    public static boolean invokeMethod(Person person) throws NoSuchMethodException,
            InvocationTargetException, IllegalAccessException {
    
    
        //从目标字节码文件中,获取目标方法
        //1.获取指定的某个方法
        Method targetMethod = Cls.getDeclaredMethod("method");
        //2.保证当前方法是可访问的
        targetMethod.setAccessible(true);

        //获取目标方法的注解中,包含的超时信息
        long timeSpan = getTimeLimit(targetMethod);
        if (timeSpan == -1) return false;

        //在目标对象上反射调用目标方法,看下目标方法的执行是否超时
        long startTime = System.currentTimeMillis();
        targetMethod.invoke(person);        //运行          加了运行时间上限注解的方法
        long endTime = System.currentTimeMillis();
        if ((endTime - startTime) >= timeSpan) {
    
    
            return true;
        }
        return false;
    }

    //获取目标方法的超时注解中的超时时间
    private static long getTimeLimit(Method targetMethod) throws NoSuchMethodException {
    
    
        //判断目标方法是否有MethodRuntimeLimit注解
        boolean annotationPresent = targetMethod.isAnnotationPresent(MethodRuntimeLimit.class);

        if (!annotationPresent) return -1;//如果该方法不包含超时注解信息,则说明不用判断超时,直接返会false,表示未超时

        //代码走到这里,说明目标方法是有超时注解的,于是从注解中获取超时时间
        MethodRuntimeLimit annotation = targetMethod.getAnnotation(MethodRuntimeLimit.class);
        long timeLimit = annotation.timeLimit();

        return timeLimit;
    }


}

//测试
public class Demo1 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        Person person = new Person();
        boolean isTimeOut = PersonFactory.invokeMethod(person);
        if (isTimeOut) {
    
    
            System.out.println("超时,方法允许的运行时间上限为100");
        } else {
    
    
            System.out.println("没有超时");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/AC_872767407/article/details/114222967