动态代理&&静态代理

代理模式的定义:代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用,通俗的来讲代理模式就是我们生活中常见的中介。动态代理和静态代理的区别在于静态代理我们需要手动的去实现目标对象的代理类,而动态代理可以在运行期间动态的生成代理类。

静态代理

静态代理模式-示例

1、为现有的类(Printer类)编写一个对应的代理类,并且让它实现和目标类相同的接口(public class PrinterProxy implements IPrinter
2、在创建代理对象时,通过构造器塞入一个目标对象

private IPrinter printer;
    public PrinterProxy(){
       this.printer = new printer();
   }

3、在代理对象的方法内部调用目标对象的同名方法。代理对象 = 增强代码 + 目标对象(原对象)

静态代理的缺陷

需要手动为每一个目标类编写对应的代理类。

动态代理

JDK提供了java.lang.reflect.InvocationHandler接口和java.lang.reflect.Proxy类,这两个类互相配合。

public interface InvocationHandler {
}

public class Proxy implements java.io.Serializable {
	    protected InvocationHandler h;
}
InvocationHandler

每一个proxy代理实例都有一个关联的InvocationHandler,在proxy代理实例调用方法时,方法调用被指派到InvocationHandlerinvoke方法。

/* <p>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 {@code invoke}
 * method of its invocation handler.
 * */
public interface InvocationHandler {
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable;
}

每一个动态代理类的InvocationHandler都必须实现InvocationHandler接口,并且每个proxy代理实例都关联了实现该接口的InvocationHandler,当通过代理对象调用一个方法时,这个方法的调用就会被转发到实现InvocationHandler接口类的invoke方法来调用。

newProxyInstance()方法
  @CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h) {
        Objects.requireNonNull(h);
        final Class<?> caller = System.getSecurityManager() == null
                                    ? null
                                    : Reflection.getCallerClass();
        /*
         * Look up or generate the designated proxy class and its constructor.
         */
        Constructor<?> cons = getProxyConstructor(caller, loader, interfaces);

        return newProxyInstance(caller, cons, h);
    }

这个方法的作用是创建一个代理对象类,有三个参数

  • loader:一个classloader对象,定义了由哪个classloader对象对生成的代理类进行加载
  • interfaces:一个interface对象数组,表示我们将要给我们的代理对象提供一组什么样的接口,如果我们提供了这样一个接口对象数组,那么也就是声明了代理类实现了这些接口,代理类就可以调用接口中声明的所有方法。
  • h:一个InvocationHandler对象

动态代理示例

https://www.zhihu.com/question/20794107/answer/811250346
https://blog.csdn.net/Dream_Weave/article/details/84183247
https://blog.csdn.net/yaomingyang/article/details/80981004

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值