1.为什么要动态代理
现在有这样一个需求:在聊天系统中,把每一个所说的话记录到日志文件里面,初学者可能是这样来设计
在speak方法中调用log方法,记录到数据库。这样设计有明显的不足:1、log方法不应该属于Person类中 2、如果改类库已经编译,我们就不能修改原有代码,在其方法内部增加代码。此时,有经验的开发者可能会想到代理模式。我们修改一下类图
我们将讲话给抽象出来,客户端使用接口声明,LogProxy与Person依赖,共同实现Speak接口,然后在LogPersonProxy中实现记录日志,这样就可以解决之前的问题。但是新问题又来了:我们必须为为委托类维护一个代理,不易管理而且增加了代码量。
2.JDK中的动态代理
JAVA的动态代理机制可以动态的创建代理并动态的处理代理方法调用,只要简单指定一组接口及为拖累对象,就能动态的获取代理类,JAVA已经给我们提供了强大的支持,其具体实现可以参照马士兵的动态代理视频。核心类是Proxy,负责创建所有代理类,并且创建的代理类都是其子类,而且这些子类继承所代理的一组接口,因此它就可以安全的转换成需要的类型,进行方法调用。InvocationHandler是调用处理器的接口,它自定义了一个invoke方法,用于机制处理在动态代理类上的方法调用,通常在该方法中实现对委托类的代理访问。相关类图如下
具体代理要实现InvocationHandler接口详细代码如下
我们可以在invoke方法中接到一下参数:Object proxy, Method method, Object[] args
其中,proxy是被代理的类,第二个参数表示被执行的委托方法,第三个参数表被执行的委托方法,我们在客户端测试一下,代码如下
3.JDK动态代理必须要接口的原因
在aspectj和cglib里面,被代理的对象要实现一个接口如上面的测试代码:
在cglib下是这样的:
JDK动态代理为什么必须使用接口?这个问题很有意思。
我们查看Proxy的源码
上面代码是创建一个代理类,我们看看getProxyClass的源码
接口类数组的长度小于65535,65535是计算机16位二进制最大数,如果大于就会内存溢出,继续往下。
从上面代码可以看出,接口名放在了一个数组里,接口类的Class的数组缓存在了了HashSet里面,之所以用Set是为了排除重复
这句代码是给新生成的代理类截取接口,JDK是这样设计的:如果接口为public,则生成到顶包底下,如果为默认修饰符,也就是修饰符为空,则会生成到接口所定义的包下,继续往下
这里是设计动态代理类的类名,JDK的设计师为"$ProxyN",其中N为从0递增的一个阿拉伯数字,加了synchronized 关键字,不会重复
上面代码是说调用class处理文件生成类的字节码,根据接口列表创建一个新类,这个类为代理类,通过JNI接口,将Class字节码文件定义一个新类,下面是newProxyInstance后面的代码
根据前面的代码Constructor cons = cl.getConstructor(constructorParams);
可以猜测到接口创建的新类proxyClassFile 不管采用什么接口,都是以下结构
public class $Proxy1 extends Proxy implements 传入的接口{
}
生成新类的看不到源代码,不过猜测它的执行原理很有可能是如果类是Proxy的子类,则调用InvocationHandler进行方法的Invoke
到现在大家都应该明白了吧,JDK动态代理的原理是根据定义好的规则,用传入的接口创建一个新类,JDK的动态代理只能代理接口中的方法,是针对接口生成代理类。
这就是为什么采用动态代理时为什么只能用接口引用指向代理,而不能用传入的类引用执行动态类。
附:Spring中的动态代理
关于Spring中的动态代理我之前写过一篇博文《对Spring.Net的AOP一些思考及应用》,里面写的比较的深在里面举得例子有点复杂,大家在第一次看的时候可以看看一个博友的《Spring.Net 面向切面AOP》
现在有这样一个需求:在聊天系统中,把每一个所说的话记录到日志文件里面,初学者可能是这样来设计
在speak方法中调用log方法,记录到数据库。这样设计有明显的不足:1、log方法不应该属于Person类中 2、如果改类库已经编译,我们就不能修改原有代码,在其方法内部增加代码。此时,有经验的开发者可能会想到代理模式。我们修改一下类图
我们将讲话给抽象出来,客户端使用接口声明,LogProxy与Person依赖,共同实现Speak接口,然后在LogPersonProxy中实现记录日志,这样就可以解决之前的问题。但是新问题又来了:我们必须为为委托类维护一个代理,不易管理而且增加了代码量。
2.JDK中的动态代理
JAVA的动态代理机制可以动态的创建代理并动态的处理代理方法调用,只要简单指定一组接口及为拖累对象,就能动态的获取代理类,JAVA已经给我们提供了强大的支持,其具体实现可以参照马士兵的动态代理视频。核心类是Proxy,负责创建所有代理类,并且创建的代理类都是其子类,而且这些子类继承所代理的一组接口,因此它就可以安全的转换成需要的类型,进行方法调用。InvocationHandler是调用处理器的接口,它自定义了一个invoke方法,用于机制处理在动态代理类上的方法调用,通常在该方法中实现对委托类的代理访问。相关类图如下
具体代理要实现InvocationHandler接口详细代码如下
public class LogProxy implements InvocationHandler {
private Object object;
public LogProxy(Object object) {
super();
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
method.invoke(this.object, args);
System.out.println("记录到数据库..");
return null;
}
public void setObject(Object object) {
this.object = object;
}
public Object getObject() {
return object;
}
}
public class PowerProxy implements InvocationHandler {
private Object object;
public PowerProxy(Object object) {
super();
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("进行权限验证..是否是黑名单..");
method.invoke(this.object, args);
return null;
}
public void setObject(Object object) {
this.object = object;
}
public Object getObject() {
return object;
}
}
我们可以在invoke方法中接到一下参数:Object proxy, Method method, Object[] args
其中,proxy是被代理的类,第二个参数表示被执行的委托方法,第三个参数表被执行的委托方法,我们在客户端测试一下,代码如下
public class Client {
/**
* @Title: main
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param args 描述
* @return void 返回类型
* @throws
*/
public static void main(String[] args) {
Person zhangsan = new Person("张三");
Zegapain jiqiren = new Zegapain("编号89757");
Speakable zhangsanProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new LogProxy(zhangsan));
Speakable jiqirenProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new LogProxy(jiqiren));
zhangsanProxy.speak("呵呵");
jiqirenProxy.speak("您好,我是机器人");
System.out.println("----------------------------");
Speakable zhangsanPowerProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new PowerProxy(zhangsan));
zhangsanPowerProxy.speak("我不是坏人");
System.out.println("----------------------------");
Speakable jiqirenPowerProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new PowerProxy(jiqirenProxy));
jiqirenPowerProxy.speak("我是您的机器人");
}
}
3.JDK动态代理必须要接口的原因
在aspectj和cglib里面,被代理的对象要实现一个接口如上面的测试代码:
Speakable zhangsanPowerProxy = (Speakable) Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[]{Speakable.class}, new PowerProxy(zhangsan));
在cglib下是这样的:
TestProxy tp = new TestProxy();
zhangsan= (Person ) tp.getProxy(Person.class);
JDK动态代理为什么必须使用接口?这个问题很有意思。
我们查看Proxy的源码
Class cl = getProxyClass(loader, interfaces);
上面代码是创建一个代理类,我们看看getProxyClass的源码
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
接口类数组的长度小于65535,65535是计算机16位二进制最大数,如果大于就会内存溢出,继续往下。
Class proxyClass = null;
/* collect interface names to use as key for proxy class cache */
String[] interfaceNames = new String[interfaces.length];
Set interfaceSet = new HashSet(); // for detecting duplicates
for (int i = 0; i < interfaces.length; i++) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
String interfaceName = interfaces[i].getName();
Class interfaceClass = null;
try {
interfaceClass = Class.forName(interfaceName, false, loader);
} catch (ClassNotFoundException e) {
}
if (interfaceClass != interfaces[i]) {
throw new IllegalArgumentException(
interfaces[i] + " 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.contains(interfaceClass)) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
interfaceSet.add(interfaceClass);
interfaceNames[i] = interfaceName;
}
从上面代码可以看出,接口名放在了一个数组里,接口类的Class的数组缓存在了了HashSet里面,之所以用Set是为了排除重复
Map cache;
synchronized (loaderToCache) {
cache = (Map) loaderToCache.get(loader);
if (cache == null) {
cache = new HashMap();
loaderToCache.put(loader, cache);
}
/*
* This mapping will remain valid for the duration of this
* method, without further synchronization, because the mapping
* will only be removed if the class loader becomes unreachable.
*/
}
/*
* Look up the list of interfaces in the proxy class cache using
* the key. This lookup will result in one of three possible
* kinds of values:
* null, if there is currently no proxy class for the list of
* interfaces in the class loader,
* the pendingGenerationMarker object, if a proxy class for the
* list of interfaces is currently being generated,
* or a weak reference to a Class object, if a proxy class for
* the list of interfaces has already been generated.
*/
synchronized (cache) {
/*
* Note that we need not worry about reaping the cache for
* entries with cleared weak references because if a proxy class
* has been garbage collected, its class loader will have been
* garbage collected as well, so the entire cache will be reaped
* from the loaderToCache map.
*/
do {
Object value = cache.get(key);
if (value instanceof Reference) {
proxyClass = (Class) ((Reference) value).get();
}
if (proxyClass != null) {
// proxy class already generated: return it
return proxyClass;
} else if (value == pendingGenerationMarker) {
// proxy class being generated: wait for it
try {
cache.wait();
} catch (InterruptedException e) {
/*
* The class generation that we are waiting for should
* take a small, bounded time, so we can safely ignore
* thread interrupts here.
*/
}
continue;
} else {
/*
* No proxy class for this list of interfaces has been
* generated or is being generated, so we will go and
* generate it now. Mark it as pending generation.
*/
cache.put(key, pendingGenerationMarker);
break;
}
} while (true);
}
String proxyPkg = null;
String proxyPkg = null; // package to define proxy class in
/*
* 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 (int i = 0; i < interfaces.length; i++) {
int flags = interfaces[i].getModifiers();
if (!Modifier.isPublic(flags)) {
String name = interfaces[i].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,
proxyPkg = ""; // use the unnamed package
}
// package to define proxy class in
/*
* 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 (int i = 0; i < interfaces.length; i++) {
int flags = interfaces[i].getModifiers();
if (!Modifier.isPublic(flags)) {
String name = interfaces[i].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,
proxyPkg = ""; // use the unnamed package
}
这句代码是给新生成的代理类截取接口,JDK是这样设计的:如果接口为public,则生成到顶包底下,如果为默认修饰符,也就是修饰符为空,则会生成到接口所定义的包下,继续往下
long num;
synchronized (nextUniqueNumberLock) {
num = nextUniqueNumber++;
}
String proxyName = proxyPkg + proxyClassNamePrefix + num;
这里是设计动态代理类的类名,JDK的设计师为"$ProxyN",其中N为从0递增的一个阿拉伯数字,加了synchronized 关键字,不会重复
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces);
try {
proxyClass = 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());
}
}
// add to set of all generated proxy classes, for isProxyClass
proxyClasses.put(proxyClass, null);
} finally {
/*
* We must clean up the "pending generation" state of the proxy
* class cache entry somehow. If a proxy class was successfully
* generated, store it in the cache (with a weak reference);
* otherwise, remove the reserved entry. In all cases, notify
* all waiters on reserved entries in this cache.
*/
synchronized (cache) {
if (proxyClass != null) {
cache.put(key, new WeakReference(proxyClass));
} else {
cache.remove(key);
}
cache.notifyAll();
}
}
return proxyClass;
}
上面代码是说调用class处理文件生成类的字节码,根据接口列表创建一个新类,这个类为代理类,通过JNI接口,将Class字节码文件定义一个新类,下面是newProxyInstance后面的代码
Constructor cons = cl.getConstructor(constructorParams);
return (Object) cons.newInstance(new Object[] { h });
根据前面的代码Constructor cons = cl.getConstructor(constructorParams);
可以猜测到接口创建的新类proxyClassFile 不管采用什么接口,都是以下结构
public class $Proxy1 extends Proxy implements 传入的接口{
}
生成新类的看不到源代码,不过猜测它的执行原理很有可能是如果类是Proxy的子类,则调用InvocationHandler进行方法的Invoke
到现在大家都应该明白了吧,JDK动态代理的原理是根据定义好的规则,用传入的接口创建一个新类,JDK的动态代理只能代理接口中的方法,是针对接口生成代理类。
这就是为什么采用动态代理时为什么只能用接口引用指向代理,而不能用传入的类引用执行动态类。
附:Spring中的动态代理
关于Spring中的动态代理我之前写过一篇博文《对Spring.Net的AOP一些思考及应用》,里面写的比较的深在里面举得例子有点复杂,大家在第一次看的时候可以看看一个博友的《Spring.Net 面向切面AOP》
参考:
《spring 3.x 企业级应用程序开发实战》
http://www.cnblogs.com/frankliiu-java/articles/1896443.html