动态代理是使用非常广泛的技术,诸如大名鼎鼎的spring、mybatis等框架都大量使用动态代理。动态代理区别于静态代理的地方在于:静态代理需要为每一个被代理类都创建一个代理类,在编译期代理类就已经生成,而动态代理则是在程序运行期动态地生成代理类,所有被代理对象的执行逻辑都被转移到InvocationHandler对象的invoke方法,在invoke方法里通过反射来调用被代理的对象方法,当然也可以执行其它的逻辑。动态代理的一个显而易见的好处是:不用为每个被代理类都手动创建一个代理类。
按照惯例,先谈使用再讲原理。举个例子先。
场景:七夕临近,公司交友社团本着消灭单身狗的美好愿景,为闷骚的程序猿(媛)们开通了月老服务,任何有心仪目标但是又羞于开口的单身程序狗都可以委托“月老”来约心中的男神女神出来。
Suitor(追求者)接口
public interface Suitor {
void sayHi(Beauty beauty);
}
Programmer(程序猿)
public class Programmer implements Suitor {
@Override
public void sayHi(Beauty beauty) {
System.out.println("Hello, " + beauty.getName() + "! Would you like to have dinner with me tonight?");
}
}
Beauty(MM)
public class Beauty {
private String name;
public Beauty(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
处理邀请MM动作的InvocationHandler
public class SuitorInvocationHandler implements InvocationHandler {
Suitor suitor;
public SuitorInvocationHandler(Suitor suitor) {
this.suitor = suitor;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(suitor, args);
}
}
测试,创建代理对象并对MM发出邀请
public class DynamicProxyTest {
@Test
public void test() {
Beauty beauty = new Beauty("MM");
InvocationHandler handler = new SuitorInvocationHandler(new Programmer());
Suitor suitor = (Suitor) Proxy.newProxyInstance(Suitor.class.getClassLoader(), new Class<?>[]{Suitor.class}, handler);
suitor.sayHi(beauty);
}
}
结果
Hello, MM! Would you like to have dinner with me tonight?
可见,代理对象成功地激发了被代理对象想执行的业务逻辑。
那么,代理对象到底是如何生成的,业务逻辑又是如何转嫁到InvocationHandler上的呢?
Proxy.newProxyInstance中调用生成代理类的逻辑 Class<?> cl = getProxyClass0(loader, intfs);
@CallerSensitive
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);
}
/*
* Look up or generate the designated proxy class.
* 生成代理类
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
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;
}
});
}
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
最终生成代理类的逻辑在Proxy.ProxyClassFactory.apply方法内
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
Class<?> interfaceClass = null;
try {
interfaceClass = Class.forName(intf.getName(), false, loader);
} catch (ClassNotFoundException e) {
}
if (interfaceClass != intf) {
throw new IllegalArgumentException(
intf + " is not visible from class loader");
}
/*
* Verify that the Class object actually represents an
* interface.
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // package to define proxy class in
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
/*
* Record the package of a non-public proxy interface so that the
* proxy class will be defined in the same package. Verify that
* all non-public proxy interfaces are in the same package.
*/
for (Class<?> intf : interfaces) {
int flags = intf.getModifiers();
if (!Modifier.isPublic(flags)) {
accessFlags = Modifier.FINAL;
String name = intf.getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
} else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}
if (proxyPkg == null) {
// if no non-public proxy interfaces, use com.sun.proxy package
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
/*
* Choose a name for the proxy class to generate.
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
真正生成类字节码文件的逻辑在byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags)。上面主要做的是接口校验、生成类名和确定代理类的访问修饰符等工作。那我们接着看看代理类具体是如何生成的吧。
private byte[] generateClassFile() {
// 将Object类中的方法添加到代理类中
this.addProxyMethod(hashCodeMethod, Object.class);
this.addProxyMethod(equalsMethod, Object.class);
this.addProxyMethod(toStringMethod, Object.class);
Class[] var1 = this.interfaces;
int var2 = var1.length;
int var3;
Class var4;
// 获取接口中的所有方法并添加到代理类中
for(var3 = 0; var3 < var2; ++var3) {
var4 = var1[var3];
Method[] var5 = var4.getMethods();
int var6 = var5.length;
for(int var7 = 0; var7 < var6; ++var7) {
Method var8 = var5[var7];
this.addProxyMethod(var8, var4);
}
}
Iterator var11 = this.proxyMethods.values().iterator();
List var12;
// 验证具有相同方法签名的方法返回类型是否相同
while(var11.hasNext()) {
var12 = (List)var11.next();
checkReturnTypes(var12);
}
Iterator var15;
try {
// 添加代理类的构造方法
this.methods.add(this.generateConstructor());
var11 = this.proxyMethods.values().iterator();
while(var11.hasNext()) {
var12 = (List)var11.next();
var15 = var12.iterator();
while(var15.hasNext()) {
ProxyGenerator.ProxyMethod var16 = (ProxyGenerator.ProxyMethod)var15.next();
// 代理类的字段都是Method类型,存储的待invoke的接口方法和从Object继承的方法
// 字段用private static修饰,10是ACC_PRIVATE和ACC_STATIC相与的结果
this.fields.add(new ProxyGenerator.FieldInfo(var16.methodFieldName, "Ljava/lang/reflect/Method;", 10));
// 生成代理类方法
this.methods.add(var16.generateMethod());
}
}
// 生成静态代码块初始化私有静态字段
this.methods.add(this.generateStaticInitializer());
} catch (IOException var10) {
throw new InternalError("unexpected I/O Exception", var10);
}
// 如果方法数量超过65535个则抛异常
if (this.methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
} else if (this.fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
} else {
this.cp.getClass(dotToSlash(this.className));
this.cp.getClass("java/lang/reflect/Proxy");
var1 = this.interfaces;
var2 = var1.length;
for(var3 = 0; var3 < var2; ++var3) {
var4 = var1[var3];
this.cp.getClass(dotToSlash(var4.getName()));
}
this.cp.setReadOnly();
ByteArrayOutputStream var13 = new ByteArrayOutputStream();
DataOutputStream var14 = new DataOutputStream(var13);
try {
var14.writeInt(-889275714);
var14.writeShort(0);
var14.writeShort(49);
this.cp.write(var14);
var14.writeShort(this.accessFlags);
var14.writeShort(this.cp.getClass(dotToSlash(this.className)));
var14.writeShort(this.cp.getClass("java/lang/reflect/Proxy"));
var14.writeShort(this.interfaces.length);
Class[] var17 = this.interfaces;
int var18 = var17.length;
for(int var19 = 0; var19 < var18; ++var19) {
Class var22 = var17[var19];
var14.writeShort(this.cp.getClass(dotToSlash(var22.getName())));
}
var14.writeShort(this.fields.size());
var15 = this.fields.iterator();
while(var15.hasNext()) {
ProxyGenerator.FieldInfo var20 = (ProxyGenerator.FieldInfo)var15.next();
var20.write(var14);
}
var14.writeShort(this.methods.size());
var15 = this.methods.iterator();
while(var15.hasNext()) {
ProxyGenerator.MethodInfo var21 = (ProxyGenerator.MethodInfo)var15.next();
var21.write(var14);
}
var14.writeShort(0);
return var13.toByteArray();
} catch (IOException var9) {
throw new InternalError("unexpected I/O Exception", var9);
}
}
}
那么生成的代理类到底长什么样子呢?通过以下代码,将内存中的代理类字节数组写入文件。
byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", Programmer.class.getInterfaces());
FileOutputStream fos = new FileOutputStream(new File("programmer.class"));
try {
fos.write(classFile);
fos.flush();
System.out.println("successfully generated proxy class file");
} catch (Exception e) {
System.out.println("failed to generate proxy class file");
}
生成的类文件:
public final class $Proxy0 extends Proxy implements Suitor {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final void sayHi(Beauty var1) throws {
try {
super.h.invoke(this, m3, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final int hashCode() throws {
try {
return (Integer)super.h.invoke(this, m0, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("com.wxy.popcorn.test.proxy.dynamic.Suitor").getMethod("sayHi", Class.forName("com.wxy.popcorn.test.proxy.dynamic.Beauty"));
m2 = Class.forName("java.lang.Object").getMethod("toString");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
不难看出,代理类的私有静态字段维护了所有接口方法和从Object继承的方法。这些方法的调用最终都转移到InvocationHandler.invoke。