动态代理
0. 简介
代理模式有两种形式:静态代理、动态代理。
1. 类图
图片来源网络
2. 示例
使用JDK中的Proxy类实现动态代理类的创建;
Proxy.newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler handler);
一般的用法:
public void proxy() throws Exception {
PlayProxy handler= new PlayProxy();
IPlay proxy= (IPlay) Proxy.newProxyInstance(
IPlay.class.getClassLoader(),
new Class[]{IPlay.class},
handler);
// 这个方法返回值为null,这是由invoke()方法返回的。
proxy.play("篮球");
}
interface IPlay {
void play(String name);
}
class PlayProxy implements InvocationHandler {
// 当IPlay.play()被调用时,invoke()也会被调用。
@Override
public Object invoke(Object proxy,
Method method,
Object[] args) throws Throwable {
System.out.println("method=" + method + " , args=" + args[0]);
// 在此处直接添加处理逻辑。
return null;
}
}
输出结果:
method=public abstract void com.example.demo.IPlay.play(java.lang.String) , args=篮球
由上面可以看出,虽然动态代理生成了接口的代理对象,但是代理类中没有实际的处理逻辑,而接口的方法也是没有实际处理逻辑的,所以要添加处理逻辑,只能在PlayProxy.invoke()中添加,这就增加了代码的耦合性。
注意: 跟静态代理相比,动态代理要少写一个代理类,因为该代理类可以通过Proxy.newProxyInstance()
方法获得。
这里涉及到三个类:
1. IPlay
2. StudentPlay
3. PlayProxy
public void proxy() throws Exception {
StudentPlay student = new StudentPlay();
PlayProxy handler= new PlayProxy(student);
IPlay proxy= (IPlay) Proxy.newProxyInstance(
IPlay.class.getClassLoader(),
new Class[]{IPlay.class},
handler);
proxy.play("篮球");//代理类执行play()方法
}
interface IPlay {
void play(String name);
}
class StudentPlay implements IPlay {
@Override
public void play(String name) {
System.out.println("StudentPlay.play(),name=" + name);
}
}
class PlayProxy<T> implements InvocationHandler {
// 实际的执行对象
T target;
public PlayProxy(T target) {
this.target = target;
}
@Override
public Object invoke(Object proxy,
Method method,
Object[] args) throws Throwable {
System.out.println("method=" + method + " , args=" + args[0]);
// 这里实际调用的是target对象中对应的方法,即StudentPlay.play("篮球");
Object result = method.invoke(target, args);
return result;
}
}
输出结果:
method=public abstract void com.example.demo.IPlay.play(java.lang.String) , args=篮球
StudentPlay.play(),name=篮球
3. 源码分析
源码基于JDK1.8
// java.lang.reflect.Proxy
public class Proxy implements java.io.Serializable {
/** parameter types of a proxy class constructor */
private static final Class<?>[] constructorParams = { InvocationHandler.class };
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h) throws IllegalArgumentException {
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
// 1.获取一个对interfaces包装后的代理class
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
// 2.将InvocationHandler.class作为代理class的构造参数
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
/*
* 3.通过构造器创建代理class的实例对象Proxy,
* 该Proxy对象内持有一个InvocationHandler实例。
*/
return cons.newInstance(new Object[]{h});
} catch (Exception e) {
// ...代码省略...
}
}
}