动态代理概述
动态代理在运行时动态创建代理类,无需手动编写代理类代码。
动态代理结构
调用者
→
代理对象
→
InvocationHandler
InvocationHandler
→
目标对象
创建动态代理
Object proxy = Proxy.newProxyInstance(
classLoader,
interfaces,
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
return method.invoke(target, args);
}
}
);
小结
- 动态代理在运行时创建
- InvocationHandler处理方法调用
- Proxy.newProxyInstance()创建代理对象
- 常用于AOP和RPC