美文网首页
2. 动态代理回顾: 动态代理是AOP的基础

2. 动态代理回顾: 动态代理是AOP的基础

作者: seacolo | 来源:发表于2018-10-11 09:50 被阅读0次

    接口和实现类:

    public interface Interface {
        void doSomething();
        void somethingElse(String arg);
    }
    public class RealObject implements Interface {
        public void doSomething() {
            System.out.println("doSomething.");
        }
        public void somethingElse(String arg) {
            System.out.println("somethingElse " + arg);
        }
    }
    

    动态代理对象处理器:

    public class DynamicProxyHandler implements InvocationHandler {
        private Object proxyed;
        
        public DynamicProxyHandler(Object proxyed) {
            this.proxyed = proxyed;
        }
        
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
            System.out.println("代理工作了.");
            return method.invoke(proxyed, args);
        }
    }
    

    测试类:

    public class Main {
        public static void main(String[] args) {
            RealObject real = new RealObject();
            Interface proxy = (Interface) Proxy.newProxyInstance(
                    Interface.class.getClassLoader(), new Class[] {Interface.class},
                    new DynamicProxyHandler(real));
            
            proxy.doSomething();
            proxy.somethingElse("zhw");
        }
    }
    

    结果:

    代理工作了.
    doSomething.
    代理工作了.
    somethingElse zhw
    

    相关文章

      网友评论

          本文标题:2. 动态代理回顾: 动态代理是AOP的基础

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