Java动态代理
发布日期:2022-02-24 11:36:06 浏览次数:10 分类:技术文章

本文共 5473 字,大约阅读时间需要 18 分钟。

什么是代理

   - 代理是一种常用的设计模式,其目的就是为其他对象提供一个代理以控制对某个对象的访问。代理类负责为委托类预处理消息,过滤消息并转发消息,以及进行消息被委托类执行后的后续处理。

为了保持行为的一致性,代理类和委托类通常会实现相同的接口,所以在访问者看来两者没有丝毫的区别。通过代理类这中间一层,能有效控制对委托类对象的直接访问,也可以很好地隐藏和保护委托类对象,同时也为实施不同控制策略预留了空间,从而在设计上获得了更大的灵活性。Java 动态代理机制以巧妙的方式近乎完美地实践了代理模式的设计理念。

 

静态代理

比如现在有一个Hello Service,

public class HelloServiceImpl implements HelloService {    public void sayHello(String name) {        System.out.println("Hi~,glad to meet U," + name);    }}

现在要在sayHello方法调用前和调用后, 执行一些额外的操作,但是又不可以修改HelloService的情况下,可以为HelloService创建一个代理类:

public class HelloServiceProxy implements HelloService{    private HelloService service;    public HelloServiceProxy(HelloService service) {        this.service = service;    }    public void sayHello(String name) throws Exception {        Method m = service.getClass().getDeclaredMethod("sayHello", String.class);        after(service, m, new Object[]{name});        service.sayHello(name);        before(service, m, new Object[]{name});    }    public void after(Object target, Method method, Object[] params) {        System.out.println(">>>>>>after the method " + method.getName() + "of " + target.getClass().getName());    }    public void before(Object target, Method method, Object[] params) {        System.out.println(">>>>>>before the method " + method.getName() + "of " + target.getClass().getName());    }}

使用该代理类

public class HelloServiceProxyTest extends TestCase {    public void testSayHello()throws Exception{        HelloService helloServiceProxy = new HelloServiceProxy(new HelloServiceImpl());        helloServiceProxy.sayHello("john");    }}

 静态代理有2个主要问题:

1. 要为每个业务类都创建相应的代理类
2. 如果业务类增加或者减少方法,代理类也要相应的做修改。
Java动态代理

先来看下

public void testDynamicProxy1() throws Exception {        HelloService helloService = new HelloServiceImpl();        Class clazz = Proxy.getProxyClass(helloService.getClass().getClassLoader(), helloService.getClass().getInterfaces());        Constructor constructor = clazz.getConstructor(new Class[]{InvocationHandler.class});        HelloService proxyHelloService = (HelloService) constructor.newInstance(new CustomInvocationHandler(helloService));        proxyHelloService.sayHello("John");    }
 

 - java.lang.reflect.Proxy:这是 Java 动态代理机制的主类,它提供了一组静态方法来为一组接口动态地生成代理类及其对象。

// 方法 1: 该方法用于获取指定代理对象所关联的调用处理器static InvocationHandler getInvocationHandler(Object proxy) // 方法 2:该方法用于获取关联于指定类装载器和一组接口的动态代理类的类对象static Class getProxyClass(ClassLoader loader, Class[] interfaces) // 方法 3:该方法用于判断指定类对象是否是一个动态代理类static boolean isProxyClass(Class cl) // 方法 4:该方法用于为指定类装载器、一组接口及调用处理器生成动态代理类实例static Object newProxyInstance(ClassLoader loader, Class[] interfaces,     InvocationHandler h)

  - java.lang.reflect.InvocationHandler:这是调用处理器接口,它自定义了一个 invoke 方法,用于集中处理在动态代理类对象上的方法调用,通常在该方法中实现对委托类的代理访问。

// 该方法负责集中处理动态代理类上的所有方法调用。第一个参数既是代理类实例,第二个参数是被调用的方法对象// 第三个方法是调用参数。调用处理器根据这三个参数进行预处理或分派到委托类实例上发射执行Object invoke(Object proxy, Method method, Object[] args)
 

使用 Java 动态代理,具体有如下四步骤:

  1. 通过实现 InvocationHandler 接口创建自己的调用处理器;
  2. 通过为 Proxy 类指定 ClassLoader 对象和一组 interface 来创建动态代理类;
  3. 通过反射机制获得动态代理类的构造函数,其唯一参数类型是调用处理器接口类型;
  4. 通过构造函数创建动态代理类实例,构造时调用处理器对象作为参数被传入。

实际使用过程我们可以直接使用 Proxy 的静态方法 newProxyInstance ,其已为我们封装了步骤 2 到步骤 4 的过程,所以简化后的过程如下

// CustomInvocationHandler实现了 InvocationHandler 接口,并能实现方法调用从代理类到委托类的分派转发InvocationHandler handler = new CustomInvocationHandler(...);// 通过 Proxy 直接创建动态代理类实例Interface proxy = (Interface)Proxy.newProxyInstance( classLoader, new Class[]{Interface.class},handler );

比如

public class CustomInvocationHandler implements InvocationHandler {    private Object target;    public CustomInvocationHandler() {    }    public CustomInvocationHandler(Object target) {        this.target = target;    }    public void setTarget(Object target) {        this.target = target;    }    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        System.out.println(">>>>>>before the method " + method.getName() + "of " + target.getClass().getName());        method.invoke(target, args);        System.out.println(">>>>>>after the method " + method.getName() + "of " + target.getClass().getName());        return null;    }
public void testDynamicProxy2() throws Exception {        //输出动态生成的class        Field field = System.class.getDeclaredField("props");        field.setAccessible(true);        Properties props = (Properties) field.get(null);        props.put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");        HelloService helloService = new HelloServiceImpl();        HelloService proxyHelloService = (HelloService) Proxy.newProxyInstance(helloService.getClass().getClassLoader(), helloService.getClass().getInterfaces(), new CustomInvocationHandler(helloService));        proxyHelloService.sayHello("John");    }

动态生成的代理类本身的一些特点:

1)包:如果所代理的接口都是 public 的,那么它将被定义在顶层包(即包路径为空),如果所代理的接口中有非 public 的接口(因为接口不能被定义为 protect 或 private,所以除 public 之外就是默认的 package 访问级别),那么它将被定义在该接口所在包(假设代理了 com.ibm.developerworks 包中的某非 public 接口 A,那么新生成的代理类所在的包就是 com.ibm.developerworks),这样设计的目的是为了最大程度的保证动态代理类不会因为包管理的问题而无法被成功定义并访问;

2)类修 饰符:该代理类具有 final 和 public 修饰符,意味着它可以被所有的类访问,但是不能被再度继承;

3)类名:格式是“$ProxyN ”,其中 N 是一个逐一递增的阿拉伯数字,代表 Proxy 类第 N 次生成的动态代理类,值得注意的一点是,并不是每次调用 Proxy 的静态方法创建动态代理类都会使得 N 值增加,原因是如果对同一组接口(包括接口排列的顺序相同)试图重复创建动态代理类,它会很聪明地返回先前已经创建好的代理类的类对象,而不会再尝试去创 建一个全新的代理类,这样可以节省不必要的代码重复生成,提高了代理类的创建效率。

4)类继承关系:该类的继承关系如图:

 

 

Proxy 类是它的父类,这个规则适用于所有由 Proxy 创建的动态代理类。而且该类还实现了其所代理的一组接口,这就是为什么它能够被安全地类型转换到其所代理的某接口的根本原因。

5)代理类的根类 java.lang.Object 中有三个方法也同样会被分派到调用处理器的 invoke 方法执行,它们是 hashCode,equals 和 toString

 

 

转载地址:https://blog.csdn.net/iteye_2582/article/details/82214211 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Design Pattern - Adapter
下一篇:【转】Design for performance - Interfaces matter

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年03月31日 10时16分33秒