动态代理模式

时间:2021-04-22 09:12:36   收藏:0   阅读:19
public class DynamicProxy {
    // 动态代理
    public static void main(String[] argsx) {
        Cat cat = new Cat();
        /**
         * 三个参数(被代理类的ClassLoader, 实现的接口的数组, InvocationHandler接口的实现)
         */
        Animal catProxy = (Animal)Proxy.newProxyInstance(Cat.class.getClassLoader(), 
                new Class[]{Animal.class}, 
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println(method.getName()+"-方法-------start-------");
                        Object invoke = method.invoke(cat, args);
                        System.out.println(method.getName()+"-方法-------end-------");
                        return invoke;
                    }
                });
        catProxy.voice();
    }
    // 被代理的类
    static class Cat implements Animal{
        @Override
        public void voice() {
            System.out.println("喵喵喵...");
        }
    }
    // 被代理的类的接口
    interface Animal{
        void voice();
    }
}

 

原文:https://www.cnblogs.com/zhouxuezheng/p/14687091.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!