动态代理

demo介绍: Foo_target这个对象有自己具体的业务实现,但是在方法执行前后需要一些准备事项的执行,所以需要一个代理者替自己负责整个运行过程;

  1. 定义Foo接口

    public interface Foo {
    
        void doSomething();
    
    }
  2. 定义Foo实现类Foo_target

    public class Foo_target implements Foo{
    
        @Override
        public void doSomething() {
            System.out.println("do my thing by myself...");
        }
    
    }
  3. 定义InvocationHandler类实现

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    public class MyInvocationHandler implements InvocationHandler{
    
        private Object target;
    
        public MyInvocationHandler(Object target) {
            this.target = target;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            //代理对象在 要代理对象做事之前 先做的事儿
            System.out.println("...pre...");
            //要代理对象 做的事儿
            Object o = method.invoke(target, args);
            //代理对象在 要代理对象做事之后 做的事儿
            System.out.println("...end...");
            return o;
        }
    
    }
    
  4. 运用动态代理

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Proxy;
    
    
    public class ProxyClass {
    
        public static void main(String[] args) 
                throws InstantiationException, 
                        IllegalAccessException, 
                        IllegalArgumentException, 
                        InvocationTargetException, 
                        NoSuchMethodException, 
                        SecurityException {
    
            //InvocationHandler中的invoke方法是代理类在执行时需要做的具体事儿, 参数是要代理对象
            InvocationHandler handler = new MyInvocationHandler(new Foo_target());
            //根据要代理对象的类加载器及其接口,实现代理对象
            Class proxyClass = Proxy.getProxyClass(Foo_target.class.getClassLoader(), new Class[] {Foo.class});
            //为代理对象添加InvocationHandler,返回具体代理实例
            Foo f = (Foo)proxyClass.getConstructor(new Class[]{InvocationHandler.class }).newInstance(new Object[]{handler});
            //代理对象替代理人做事儿
            f.doSomething();
    
    
            System.out.println("-------------------------------------");
            //法二
            Foo f2 = (Foo)Proxy.newProxyInstance(Foo_target.class.getClassLoader(), Foo_target.class.getInterfaces(), handler);
            f2.doSomething();
        }
    
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值