我曾多次想知道这个问题,并最终写出以下开头:
注释:
package main;
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 Clocking {
}
对象的接口:
package main;
public interface Examples {
@Clocking
void thisIsAMethod();
void thisIsAnotherMethod(String something);
@Clocking
void thisIsALongRunningMethod();
}
一个调用处理程序:
package main;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.Instant;
public class ExamplesInvocationHandler implements InvocationHandler {
private Examples examples = new ExamplesImpl();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(!method.isAnnotationPresent(Clocking.class)) {
return method.invoke(examples, args);
}
Instant start = Instant.now();
Object returnObj = method.invoke(examples, args);
Instant end = Instant.now();
System.out.println("Method " + method.getName() + " executed in " + Duration.between(end, start) + ".");
return returnObj;
}
private static class ExamplesImpl implements Examples {
@Override
public void thisIsAMethod() {
System.out.println("thisIsAMethod called!");
}
@Override
public void thisIsAnotherMethod(String something) {
System.out.println("thisIsAnotherMethod called!");
}
@Override
public void thisIsALongRunningMethod() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thisIsALongRunningMethod called!");
}
}
}
最后,这是一个测试此功能的入口点:
package main;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
Examples examples = (Examples) Proxy.newProxyInstance(Examples.class.getClassLoader(), new Class[]{Examples.class}, new ExamplesInvocationHandler());
examples.thisIsAMethod();
examples.thisIsAnotherMethod("");
examples.thisIsALongRunningMethod();
}
}
这需要改进,因为它需要代理来实例化我们的对象,所以你不能真正用它来处理 "通用已编写" 的代码。但它可能会带领你找到更完整的解决方案。