Java动态代理

参考来源:

  • Java动态代理视频
  • JDK动态代理实现原理
  • JDK Dynamic Proxies
  • Building simple proxies

代码

  • ServiceOne.java
public interface ServiceOne {

    String sayHello();
}
  • ServiceOneBean.java
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;
    }
}
  • LogTimeProxyTest.java
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);
        
    }
}

你可能感兴趣的:(Java动态代理)