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:
Here's how your TimeCounterDemo
may look like:
TimeCounter (Annotation)
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 (Interface)
public interface ITimerCounterDemo {
@TimeCounter
public void trackMyTimeSpentUsingAnnotation();
public void someOtherMethod(int a);
}
TimerCounterDemo (Implementation of above interface)
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);
}
}
Testing the timer:
public class TimerTest {
public static void main(String[] args) throws InterruptedException {
ITimerCounterDemo t = (ITimerCounterDemo) TimerProxy.newInstance(new TimerCounterDemo());
t.someOtherMethod(10);
t.trackMyTimeSpentUsingAnnotation();
}
}
Output:
In someothermethod with value:: 10
TimerCounterDemo:: Going to sleep
TimerCounterDemo:: Completed.
trackMyTimeSpentUsingAnnotation executed in 2 seconds
You can read more about it here and here