标签:style blog io ar color os 使用 sp java
最近用到了java的动态代理,虽然会用,但不了解他具体是怎么实现,抽空看看了看他的源码。
说到Java的动态代理就不能不说到代理模式,动态代理也就是多了一个’动态’两字,在《大话设计模式》中不是有这句话吗?“反射,反射程序员的快乐”,这里也不例外,他在底层也是使用了反射来创建对象。
一、 为了让我们更加明白的了解动态代理,我们先来复习一下代理模式吧(没有学过的,也得假装复习是复习呀,不然掉面)。
public interface BookManager {
void addBook();
}
1 package com.test; 2 3 public class Library implements BookManager { 4 5 public void addBook() { 6 // TODO Auto-generated method stub 7 System.out.println("增加图书。。。。。"); 8 } 9 10 }
1 package com.test; 2 3 public class Agent implements BookManager { 4 private BookManager library; 5 6 public BookManager getLibrary() { 7 return library; 8 } 9 10 public void setLibrary(BookManager library) { 11 this.library = library; 12 } 13 14 public void addBook() { 15 // TODO Auto-generated method stub 16 System.out.println("添加图书之前"); 17 library.addBook(); 18 System.out.println("添加图书之后"); 19 } 20 21 }
测试代码
package com.test;
public class BookTest {
public static void main(String[] args) {
BookManager library = new Library();
Agent agent = new Agent();
agent.setLibrary(library);
agent.addBook();
}
}
执行结果为
添加图书之前
增加图书。。。。。
添加图书之后
从这里可以看到在代理模式中要求是都实现了相同的接口,所以这样的代码,移植性不强,所以催生出动态代理。动态代理不要求,必须实现相同的接口,减少了代码量。
先上代码
public interface BookFacade {
public void addBook();
}
public class BookFacadeImpl implements BookFacade,system {
public void addBook() {
// TODO Auto-generated method stub
System.out.println("增加图书方法。。。");
}
public void doSys() {
// TODO Auto-generated method stub
System.out.println("dsfsdfsd");
}
}
public class BookFacadeProxy implements InvocationHandler {
private Object target;
/**
* 绑定委托对象并返回一个代理类
* @param target
* @return
*/
public Object bind(Object target) {
this.target = target;
//取得代理对象
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this); //要绑定接口(这是一个缺陷,cglib弥补了这一缺陷)
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result=null;
System.out.println("事物开始");
//执行方法
System.out.println("ClassLoad"+proxy.getClass().getSimpleName());
result=method.invoke(target, args);
System.out.println("事物结束");
return result;
}
}
public class TestProxy {
public static void main(String[] args) {
BookFacadeProxy proxy = new BookFacadeProxy();
BookFacade bookProxy = (BookFacade) proxy.bind(new BookFacadeImpl());
bookProxy.addBook();
ProxyGeneratorUtils.writeProxyClassToHardDisk("F:/$Proxy11.class");
}
}
我先声明后面这段代码我盗用了其他网友的成果。
先说明用法,再来解释为什么会是这样的呢?
第一步 你必须得声明一个接口,而且在目标类必须实现这个接口,不然你使用动态代理是不会成功的。
第二步 需要实现 InvocationHandler 接口,创建一个代理类,这个代理类里需要重写invoke方法,在这个方法里,需要写上多被代理对象的调用method.invoke(target, args),如果不知道method.invoke()是做什么用的,可以去看看反射就明白了。参数有两个一个是被代理的对象,第二个就是调用该方法的参数
第三步 需要获得代理对象,可以通过Object Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
方法来生成一个代理对象。
具体的第一个是使用那一个类加载器加载,第二个就是需要绑定的接口,第三个就是持有处理的对象。
测试方法安装你正常调用相应的方法就行。
测试类执行结果如下
事物开始 增加图书方法。。。 事物结束
现在我们知道用法了,按照我们一般考虑问题的思路是,
生成的代理对象,能调用接口的的方法,肯定是实现了接口这是我们的猜想一,这个涉及到代理对象的生成。
第二个调用addBook方法,能执行,invoke方法,他是怎么调用的呢。
那么我们现在就进入源码吧,先来看看对象是怎么生成的。
Returns an instance of a proxy class for the specified interfaces
that dispatches method invocations to the specified invocation
handler.
看看注释就明白了,返回一个代理类的对象,而且还是实现了你进来接口的类
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
if (h == null) {
throw new NullPointerException();
}
/*
* 生成一个代理类
*/
Class<?> cl = getProxyClass(loader, interfaces);
/*
* 通过反射用构造方法生成一个对象
*/
try {
Constructor cons = cl.getConstructor(constructorParams);
return cons.newInstance(new Object[] { h });
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString());
} catch (IllegalAccessException e) {
throw new InternalError(e.toString());
} catch (InstantiationException e) {
throw new InternalError(e.toString());
} catch (InvocationTargetException e) {
throw new InternalError(e.toString());
}
}
上面大家可以看到,生成了一个对象返回去了,这个对象就是我们所说的代理对象,那么我们可以看看这个class 是怎么生成?
public static Class<?> getProxyClass(ClassLoader loader,
Class<?>... interfaces)
throws IllegalArgumentException
{
验证接口的长度
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
这个class 对象就是我们被返回对象的定义
Class<?> proxyClass = null;
/* collect interface names to use as key for proxy class cache */
String[] interfaceNames = new String[interfaces.length];
// for detecting duplicates
Set<Class<?>> interfaceSet = new HashSet<>();
for (int i = 0; i < interfaces.length; i++) {
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;
}
....... 中间省略N多
生成一个代理class文件,这个就是我们要被返回的class 对象
/*
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces);
try {
proxyClass = defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
这样我们就知道这个代理对象是怎么生成的。
接下来我们第2个问题就是这个invoke 方法是什么时候调用的。
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces);
从这个方法我们可以看出来,他可以生成一个二进制的文件,那么我们把这个文件写到本地就可以看到这个文件了。
public final class $Proxy110 extends Proxy
implements BookFacade
{
private static Method m1;
private static Method m3;
private static Method m0;
private static Method m2;
public $Proxy110(InvocationHandler paramInvocationHandler)
throws
{
super(paramInvocationHandler);
}
public final boolean equals(Object paramObject)
throws
{
try
{
return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final void addBook()
throws
{
try
{
this.h.invoke(this, m3, null);
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
这个是生成
标签:style blog io ar color os 使用 sp java
原文地址:http://www.cnblogs.com/2014----/p/4050886.html