本博客阅读的前提:了解Class对象,可以参考:https://blog.csdn.net/river66/article/details/103606336
java实现动态代理利用的是java的反射机制,我们会使用Proxy.newProxyInstance()生成代理类。如:
public interface Movable {
void move();
}
public class Mouse implements Movable {
@Override
public void move() {
System.out.println("老鼠跑得快!");
}
}
final Movable movable = new Mouse();
Class<?> movableClass = movable.getClass();
Movable proxy = (Movable) Proxy.newProxyInstance(movableClass.getClassLoader(),
movableClass.getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("猫抓老鼠!");
Object result = method.invoke(movable, args);
System.out.println("老鼠还是被抓到了!");
return result;
}
});
proxy.move();
打印:
猫抓老鼠!
老鼠跑得快!
老鼠还是被抓到了!
要使用java自带的api完成动态代理,前提条件就是目标类必须实现接口!(如上面的Movable接口)
还有一种动态代理可以不用实现接口,那就是Cglib动态代理,它的原理是生成目标类的子类当做代理类。
因为代理类对象是需要强转为目标类对象以供程序使用的,所以要么是使用接口持有目标类对象的引用,要么是子类强转为父类(满足里氏代换原则)
下面重点分析Proxy.newProxyInstance()函数中,是如何利用java的反射机制实现的???(未搞定)
根据分析源码,我提取了关键的代码如下:
//为了使用Proxy类中的私有方法:defineClass0(Native方法),需要利用反射技术来进行调用
Class proxyClass = Class.forName("java.lang.reflect.Proxy");
Constructor[] constructors = proxyClass.getDeclaredConstructors();
constructors[0].setAccessible(true);
Proxy proxy = (Proxy) constructors[0].newInstance();
Method method = proxyClass.getDeclaredMethod("defineClass0", ClassLoader.class, String.class, byte[].class, int.class, int.class);
method.setAccessible(true);
String proxyName = "com.river.MyProxy";
Movable mouse = new Mouse();
Class mouseClass = mouse.getClass();
Class<?>[] intfs = mouseClass.getInterfaces().clone();
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
//动态生成com.river.MyProxy.class文件对应的字节数据
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, intfs, accessFlags);
//调用defineClass0方法,生成com.river.MyProxy.class对应的Class对象。
Class mouseProxyClass = (Class) method.invoke(proxy, mouseClass.getClassLoader(), proxyName, proxyClassFile, 0, proxyClassFile.length);
System.out.println("生成的代理类对应的Class对象:"+mouseProxyClass.getName());
Class<?>[] constructorParams = { InvocationHandler.class };
Constructor<?> cons = mouseProxyClass.getConstructor(constructorParams);
InvocationHandler h = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(method.getName()+"被调用");
//注意:这里调用method.invoke()是会发生错误的!!
return null;
}
};
//必须将h对象通过构造函数传入,这样该对象的invoke方法才会被动态生成的代理对象所调用
Movable proxyMouse = (Movable) cons.newInstance(new Object[]{h});
proxyMouse.move();
打印:
生成的代理类对应的Class对象:com.river.MyProxy
move被调用
上面的例子虽然可以跑起来,但是逻辑是不对的,只是为了演示大概流程。因为生成.class字节数据和defineClass0()方法的实现细节,以及InvocationHandler h这个对象是如何被这个动态生成的代理对象所使用的,本人还没有弄清楚!如果有大神可以指点一二,感激不尽!!