当前位置:网站首页>Dynamic proxy

Dynamic proxy

2022-06-25 12:16:00 User 9854323

Application scenario of agent mode :

1、 For example, to add monitoring to a method , Record the time when the method started , Time at the end of the method .

Static proxy :

Disadvantages of static proxy : Interface and proxy classes are 1 Yes 1 Of , There are multiple interfaces that need proxies , You need to create multiple proxy classes , tedious , Class blast .

    public interface IPerson {
        void say();
    }

    public static class Man implements IPerson{
        @Override
        public void say() {
        }
    }

    /**
     *  Disadvantages of static proxy : Interface and proxy classes are 1 Yes 1 Of , There are multiple interfaces that need proxies , You need to create multiple proxy classes , tedious , Class blast .
     *  So there is a dynamic proxy 
     */
    public class ManProxy implements IPerson{

        private IPerson target;

        public IPerson getTarget() {
            return target;
        }

        public ManProxy setTarget(IPerson target) {
            this.target = target;
            return this;
        }

        @Override
        public void say() {
            if (target != null) {
                // Such as monitoring say Method start time 
                target.say();
                // Such as monitoring say End time of method 
            }
        }
    }

A dynamic proxy :

    /**
     *  A dynamic proxy 
     */
    public static class NormalHandler implements InvocationHandler {

        private Object target;

        public NormalHandler(Object target) {
            this.target = target;
        }

        // The first parameter is the proxy object , The second parameter is the called method object , The third method is the call parameter .
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            // Such as monitoring target Method start time 
            method.invoke(target, args);
            // Such as monitoring target End time of method 
            return null;
        }
    }

    /**
     *  Call of dynamic proxy 
     */
    public static void main(String[] args) {
        Man man = new Man();
        IPerson iPerson = (IPerson) Proxy.newProxyInstance(
                man.getClass().getClassLoader(),   //ClassLoader
                man.getClass().getInterfaces(),    //interfaces
                new NormalHandler(man));           //InvocationHandler
        iPerson.say();
    }
原网站

版权声明
本文为[User 9854323]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251146400866.html