美文网首页
Java动态代理

Java动态代理

作者: 秦汉邮侠 | 来源:发表于2016-02-23 01:01 被阅读93次

    参考来源:

    代码

    • 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动态代理

          本文链接:https://www.haomeiwen.com/subject/pxmbkttx.html