Java的动态代理相较于代理的思想更向前迈进了一步,因为它可以动态地创建代理并动态地处理对所代理方法的调用。在动态代理上所做的所有调用都会被重定向到单一的调用处理器上,它的工作是揭示调用的类型并确定相应的对策。
一个简单的动态代理的例子:
public class ProxyTest01 {
public static void main(String[] args){
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
IInterface i = (IInterface) Proxy.newProxyInstance(IInterface.class.getClassLoader(), new Class[]{IInterface.class}, new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("动态代理-----");
System.out.println(method.getName());
System.out.println(Arrays.toString(args));
return null;
}
});
i.show("hahaha");
System.out.println(i.getClass().getName());
}
public interface IInterface {
void show(String msg);
}
}
}
运行后的打印结果为:
动态代理-----
show
[hahaha]
com.sun.proxy.$Proxy0
可以看到,但我们调用i.show("hahaha")时,invoke()会对其进行拦截,因此输出了invoke()中的打印语句。这是如何实现的呢?
我们看到,i输出的类型时com.sun.proxy.$Proxy0,这个东西是啥,我们应该找到它一探究竟。
很简单,只需要在main()第一行加入如下代码:
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
然后编译、运行后,会在根目录自动创建com.sun.proxy目录,在这个目录下就会生成我们想要的$Proxy01.class 因为它是一个字节码文件,因此我们用javap命令将其反编译,得到:
public final class com.sun.proxy.$Proxy0 extends java.lang.reflect.Proxy implements com.hyts.day04.proxytest.ProxyTest01$IInterface {
public com.sun.proxy.$Proxy0(java.lang.reflect.InvocationHandler) throws ;
public final boolean equals(java.lang.Object) throws ;
public final java.lang.String toString() throws ;
public final void show(java.lang.String) throws ;
public final int hashCode() throws ;
static {} throws ;
}
大致可以看出来它继承Proxy,并且实现了IInterface接口。想知道更多的细节,我们可以继续用javap -c 命令来将其反编译为jvm字节码,为了方便阅读,我们使用上一张用到的jad工具对其进行操作,通过./jad -sjava xx.class 命令后得到$Proxy.java文件,打开后:
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
package com.sun.proxy;
import java.lang.reflect.*;
public final class $Proxy0 extends Proxy
implements com.hyts.day04.proxytest.ProxyTest01.IInterface
{
public $Proxy0(InvocationHandler invocationhandler)
{
super(invocationhandler);
}
public final boolean equals(Object obj)
{
try
{
return ((Boolean)super.h.invoke(this, m1, new Object[] {
obj
})).booleanValue();
}
catch(Error _ex) { }
catch(Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
public final String toString()
{
try
{
return (String)super.h.invoke(this, m2, null);
}
catch(Error _ex) { }
catch(Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
public final void show(String s)
{
try
{
super.h.invoke(this, m3, new Object[] {
s
});
return;
}
catch(Error _ex) { }
catch(Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
public final int hashCode()
{
try
{
return ((Integer)super.h.invoke(this, m0, null)).intValue();
}
catch(Error _ex) { }
catch(Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
private static Method m1;
private static Method m2;
private static Method m3;
private static Method m0;
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] {
Class.forName("java.lang.Object")
});
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m3 = Class.forName("com.hyts.day04.proxytest.ProxyTest01$IInterface").getMethod("show", new Class[] {
Class.forName("java.lang.String")
});
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
}
catch(NoSuchMethodException nosuchmethodexception)
{
throw new NoSuchMethodError(nosuchmethodexception.getMessage());
}
catch(ClassNotFoundException classnotfoundexception)
{
throw new NoClassDefFoundError(classnotfoundexception.getMessage());
}
}
}
我们直接看实现的show():
public final void show(String s)
{
try
{
super.h.invoke(this, m3, new Object[] {
s
});
return;
}
catch(Error _ex) { }
catch(Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
直接调用了super.h.invoke(this,m3,new Object[]{}),那这个h是什么呢,我们看它的父类Proxy就知道了,在Proxy中有我们找到了:
protected InvocationHandler h;
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
原来h就是$Proxy0在其构造函数中传入的InvocationHandler
public $Proxy0(InvocationHandler invocationhandler)
{
super(invocationhandler);
}
再继续看m3,它是什么呢?
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] {
Class.forName("java.lang.Object")
});
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m3 = Class.forName("com.hyts.day04.proxytest.ProxyTest01$IInterface").getMethod("show", new Class[] {
Class.forName("java.lang.String")
});
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
}
catch(NoSuchMethodException nosuchmethodexception)
{
throw new NoSuchMethodError(nosuchmethodexception.getMessage());
}
catch(ClassNotFoundException classnotfoundexception)
{
throw new NoClassDefFoundError(classnotfoundexception.getMessage());
}
}
在$Proxy0的静态代码块中,通过反射得到IInterface的class对象,这就是m3.
这样总体看起来一切就清楚了,$Proxy0中的show()方法其实最终就是重定向到了InvocationHandler的invoke()中了,因此当我们调用i.show()方法时,就会被InvocationHandler的invoke()方法拦截,而我们又传入了具体的IInterface代理对象(这里我们没有创建IInterface的代理),这样就可以在invoke()中听过传入的代理对象对其方法进行一些列操作,实现动态代理。
好了,动态代理的分析就到这儿了。