Java动态代理

♀尐吖头ヾ 提交于 2020-01-20 03:02:33

动态代理

  • 特点:字节码随用随创建,随用随加载
  • 作用:不修改源码的基础上对方法增强
  • 分类
    • 基于接口的动态代理
      • Proxy
    • 基于子类的动态代理
      • Enhancer

创建代理对象

  • 基于接口的动态代理
    • 使用proxy类中的newProxyInstance方法
    • 要求:被代理类最少实现一个接口,若果没有则不能使用
    • newProxyInstance方法的参数
  • 基于子类的动态代理
    • 使用Ehancer中的create方法
    • 被代理类不能是最终类

newProxyInstance方法的参数

  • ClassLoader:类加载器
  • Class[]:字节码数组
  • InvocationHandler:提供增强的代码
    • 参数
      • proxy:代理对象的引用
      • method:当前执行的方法
      • args:当前执行方法所需的参数
      • return:被代理方法返回值

create方法参数

  • Class:字节码
  • Callback用于提供增强的代码
    • object:代理对象的引用
    • method:当前执行的方法
    • args:当前执行方法所需的参数
    • methodproxy:当前执行方法的代理对象

接口动态代理

final ProducerImpl producer = new ProducerImpl();
Producer produceri = (Producer) Proxy.newProxyInstance(producer.getClass().getClassLoader(),
                producer.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Float money = (Float) args[0];
                        Object object = null;
                        if (method.getName().equals("sale")) {
                            object = method.invoke(producer, money * 0.9f);
                        }
                        return object;
                    }
                });
produceri.sale(1000f);

子类动态代理

final Producer producer = new Producer();
Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Float money = (Float) objects[0];
                Object object = null;
                if (method.getName().equals("sale")) {
                    object = method.invoke(producer, money * 0.9f);
                }
                return object;
            }
        });
cglibProducer.sale(1000f);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!