美文网首页
动态代理

动态代理

作者: 咚了个汐 | 来源:发表于2018-10-29 14:54 被阅读5次
    public interface Subject {
        public void doSome();
    }
    
    public class Aminor implements Subject {
        public void doSome() {
            System.out.println("被代理对象执行");
        }
    }
    
    public class AminorProxy implements InvocationHandler {
        private Object tar;
    
        public Object bind(Object tar) {
            this.tar = tar;
            return Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this);
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            // TODO Auto-generated method stub
            Object result = null;
            System.out.println("被代理对象执行前执行的事");
            result = method.invoke(tar, args);
            System.out.println("被代理对象执行后执行的事");
            return result;
        }
    
    }
    
    public class Test {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            AminorProxy proxy = new AminorProxy();
            Subject sub = (Subject) proxy.bind(new Aminor());
            sub.doSome();
        }
    }
    

    相关文章

      网友评论

          本文标题:动态代理

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