参考来源:
代码
public interface ServiceOne {
String sayHello();
}
public class ServiceOneBean implements ServiceOne {
@Override
public String sayHello()
{
System.out.println("Execute method sayHello");
return "hello";
}
}
- LogExecutionTimeProxy.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class LogExecutionTimeProxy implements InvocationHandler {
//The target instance
private Object invocationTarget;
public LogExecutionTimeProxy(Object invocationTarget)
{
this.invocationTarget = invocationTarget;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
//Start time
long startTime = System.nanoTime();
//Invoke the method on the target instance
Object result = method.invoke(invocationTarget, args);
//Print the execution time
System.out.println("Executed method " + method.getName() + " in "
+ (System.nanoTime() - startTime) + " nanoseconds");
//Return the result to the caller
return result;
}
}
import java.lang.reflect.Proxy;
public class LogTimeProxyTest {
public static void main(String[] args)
{
//Create the target instance
ServiceOne serviceOne = new ServiceOneBean();
//Create the proxy
ServiceOne proxy = (ServiceOne)Proxy.newProxyInstance(ServiceOne.class.getClassLoader()
, serviceOne.getClass().getInterfaces()
, new LogExecutionTimeProxy(serviceOne));
String result = proxy.sayHello();
System.out.println("Result: " + result);
}
}