Java 动态代理(proxy、invocationHandler)

首先要明白其中的概念:

**Handler: 处理者。处理业务逻辑等事情。

**Proxy:代理者。交给我来代理,我帮你管理事情,我出面去做本该你做的事情!我是抛头露面的侍者。

/*原接口,即将被委托给代理者*/public interface MyInterface {public void execute();}</pre><span style="font-size:14px"></span><pre name="code" class="java">/*原接口实现*/public class MyInterfaceImpl implements MyInterface {@Overridepublic void execute() {System.out.println("execute() be called");}}创建代理: (MyInterface) Proxy.newProxyInstance(myInterfaceImpl.getClass().getClassLoader(),myInterfaceImpl.getClass().getInterfaces(),handler);//Proxy.newProxyInstance(para1,para2,para3)

1.para1 被代理类(原接口实现)的类加载器 classLoader(里面放了一些静态资源.class等等,,不详述)

2.para2 被代理类 实现的所有接口

3.para3 (传入了被代理类的 )处理者

这段代码运行后,代理产生,所有对代理的调用将被转发给handler,也就是转发给InvocationHandler接口的实现类。

(—All method calls to the dynamic proxy are forwarded to thisInvocationHandlerimplementation)

import java.lang.reflect.Proxy;public class Client {public static void main(String[] args) {// 我的接口实现 被代理对象MyInterface myInterfaceImpl = new MyInterfaceImpl();// 处理者 业务代理类BusinessHandler handler = new BusinessHandler(myInterfaceImpl);// 代理者 获得代理类($Proxy0 extends Proxy implements MyInterface)的实例.MyInterface MyInterfaceProxy = (MyInterface) Proxy.newProxyInstance(myInterfaceImpl.getClass().getClassLoader(), myInterfaceImpl.getClass().getInterfaces(), handler);MyInterfaceProxy.modify();}}

import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;/*InvocationHandler 处理者类*/public class BusinessHandler implements InvocationHandler {private Object object = null;public BusinessHandler(Object object) {this.object = object;}/** * * @param proxy 就是代理者, 一般没什么用 * @param method 代理者调用的方法,使用了反射机制,可以动态获取该方法的所有信息。 * @param args 被调用方法需要的参数(不需要则无所谓) * **/@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {System.out.println("do something before method");Object ret = method.invoke(this.object, args);System.out.println("do something after method");return ret;}}

参考链接:

(反射)

勇于接受自己的失败,告诉自己,这就是自己的现实,

Java 动态代理(proxy、invocationHandler)

相关文章:

你感兴趣的文章:

标签云: