• 基于接口的 InvocationHandler 动态代理(换种写法)


    InvocationHandler is the interface implemented by the invocation handler of a proxy instance.

    Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.

    package cn.zno.newstar.base.utils.text;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class ProxyDemo {
        public static void main(String[] args) {
            Target target = new TargetImpl();
            TargetIH ih = new TargetIH();
            Target proxy = ih.newProxyInstance(target);
            proxy.doSomething();
            proxy.doSomethingElse();
        }
    }
    
    interface Target {
        void doSomething();
    
        void doSomethingElse();
    }
    
    class TargetImpl implements Target {
    
        @Override
        public void doSomething() {
            System.out.println("TargetImpl doSomething");
        }
    
        @Override
        public void doSomethingElse() {
            System.out.println("TargetImpl doSomethingElse");
        }
    }
    
    class TargetIH implements InvocationHandler {
        private Object target;
    
        @SuppressWarnings("unchecked")
        public <T> T newProxyInstance(T target) {
            this.target = target;
            Class<?> clazz = target.getClass();
            // a proxy instance 的 invocation handler 实现 InvocationHandler 接口
            return (T) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) {
            System.out.println("proxy start");
            Object result = null;
            /* 
             * 这里可以正则方法名,判断参数,判断注解;不同场景动态代理不同的事
             * 
             * */
            try {
                result = method.invoke(target, args);
            } catch (Exception e) {
                // do something
            }
            System.out.println("proxy end");
            return result;
        }
    }

    结果:

    proxy start
    TargetImpl doSomething
    proxy end
    proxy start
    TargetImpl doSomethingElse
    proxy end
  • 相关阅读:
    DFC-3C和DFC-3B的区别和注意事项
    Bug搬运工-CSCux99539:Intermittent error message "Power supply 2 failed or shutdown"
    EVE上传Dynamips、IOL和QEMU镜像
    EVE扩大虚拟内存
    EVE磁盘扩容
    VMware安装EVE
    介绍Mobility Group
    Bug搬运工-CSCvi02106 :Cisco 2800, 3800, 1560 APs: when connected to a Cisco Switch CDP-4-DUPLEX_MISMATCH log is seen
    jquery.autocomplete在火狐下的BUG解决
    nodeJS中exports和mopdule.exports的区别
  • 原文地址:https://www.cnblogs.com/zno2/p/9153027.html
Copyright © 2020-2023  润新知