用Java编写自定义注释-TimeCounter注释示例 [英] Writing custom annotations in java - TimeCounter annotation example

查看:89
本文介绍了用Java编写自定义注释-TimeCounter注释示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要跟踪使用自定义注释的方法所花费的时间.(我知道可以使用spring AOP,但是我们不能在产品中使用它.)

Basically I have a requirement to track time spent in a method using custom annotation. (I know spring AOP can be used for this, but we can not use it in our product).

public class TimeCounterDemo {
    
    @TimeCounter
    public void trackMyTimeSpentUsingAnnotation()
    {
        //some heavy processing stuff
    }   
}

public @interface TimeCounter {
  //need help with this implementation.
}

因此,我的要求是完成 TimeCounter 批注.要求很简单-

So, my requirement is to complete the TimeCounter annotation. The requirement are simple -

  1. 方法开始的记录时间.
  2. 方法结束的记录时间.
  3. 记录在方法上花费的总时间.
  4. 执行的方法名称

有人可以帮助您实现上述要求的注释.

Could someone help on how to implement this annotation to above requirements.

谢谢.

推荐答案

已经有许多带有此类注释的库.如果您想要自己的实现,则其中一种方法是使用

There are already many libraries that have such annotations available. If you want your own implementation, one of the appraoches would be to use dynamic proxies:

您的 TimeCounterDemo 如下所示:

TimeCounter(注释)

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

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

}

ITimerCounterDemo(接口)

public interface ITimerCounterDemo {
    @TimeCounter // proxy can detect annotation at interface level
    public void trackMyTimeSpentUsingAnnotation();

    public void someOtherMethod(int a);
}

TimerCounterDemo(上述界面的实现)


public class TimerCounterDemo implements ITimerCounterDemo {
    
    public void trackMyTimeSpentUsingAnnotation() {
        System.out.println("TimerCounterDemo:: Going to sleep");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        System.out.println("TimerCounterDemo:: Completed.");
    }

    public void someOtherMethod(int a) {
        System.out.println("In someothermethod with value:: " + a);
    }
}

TimerProxy

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Objects;

public class TimerProxy implements InvocationHandler {

    private Object targetObj;

    public static Object newInstance(Object targetObj) {
        Objects.requireNonNull(targetObj);
        return Proxy.newProxyInstance(
                      targetObj.getClass().getClassLoader(), 
                      targetObj.getClass().getInterfaces(),
                      new TimerProxy(targetObj)
               );
    }

    private TimerProxy(Object targetObj) {
        this.targetObj = targetObj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.isAnnotationPresent(TimeCounter.class)) {

            LocalDateTime start = LocalDateTime.now();
            Object returnObj = method.invoke(targetObj, args);

            System.out.println(method.getName() + " executed in "
                    + Duration.between(start, LocalDateTime.now()).getSeconds() + " seconds");
            return returnObj;
        }

        return method.invoke(targetObj, args);
    }

}

测试计时器:

public class TimerTest {
    public static void main(String[] args) throws InterruptedException {
        ITimerCounterDemo t = (ITimerCounterDemo) TimerProxy.newInstance(new TimerCounterDemo());
        t.someOtherMethod(10);
        t.trackMyTimeSpentUsingAnnotation();
    }
}

输出:

In someothermethod with value:: 10
TimerCounterDemo:: Going to sleep
TimerCounterDemo:: Completed.
trackMyTimeSpentUsingAnnotation executed in 2 seconds

您可以在此处 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆