Java动态代理

参考来源:

代码

  • 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动态代理通过反射的机制实现在运行时,基于传入的指定一组接口及委托类对象,动态的产生代理类,代理类负责...
    Justlearn阅读 998评论 1 10
  • 在工作之余看一些优秀源码的时候发现很多地方使用了动态代理,所以抽了一些时间对java的动态代理深入熟悉一下,这篇文...
    半支铅笔半块橡皮阅读 513评论 0 3
  • Java动态代理技术广泛的应用于我们的项目之中,比如Spring AOP、分布式服务框架等。其主要实现方式有2种,...
    anseey阅读 1,546评论 0 0
  • 背景:学习spring的AOP或者EasyMock的源码时,需要对java的动态代理有深刻的了解 关于cglib的...
    测试你个头阅读 785评论 0 1
  • Day 4 瞎逛 温泉?足疗? ❤️预约商务7座提前一个小时到机场 ❤️回家辣
    MMUP阅读 175评论 0 0