标签:动态代理 proxy invocationhandler java
首先要明白其中的概念:
**Handler: 处理者。处理业务逻辑等事情。
**Proxy:代理者。交给我来代理,我帮你管理事情,我出面去做本该你做的事情!我是抛头露面的侍者。
/*原接口,即将被委托给代理者*/
public interface MyInterface {
public void execute();
}/*原接口实现*/
public class MyInterfaceImpl implements MyInterface {
@Override
public 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 thisInvocationHandler implementation)
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 被调用方法需要的参数(不需要则无所谓)
* **/
@Override
public 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;
}
}参考链接:
http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html (反射)
http://hi.baidu.com/malecu/item/9e0edc115cb597a1feded5a0
Java 动态代理(proxy、invocationHandler)
标签:动态代理 proxy invocationhandler java
原文地址:http://blog.csdn.net/lemon89/article/details/44116119