Java动态代理
代理是对某个对象,在调用方法前后做事情。静态代理对某个给定对象做代理,动态代理是给定的对象不确定。这里主要讲的是动态代理,下面是实现源码。
interface ITest{
void a();
void b();
}
class Test implements ITest{
@Override
public void a() {
System.out.printf("a");
}
@Override
public void b() {
System.out.printf("b");
}
}
class Invocation implements InvocationHandler {
Object object;
public Invocation(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before method run..."+method);
final Object invoke = method.invoke(object, args);
System.out.println("after method run..."+method);
return invoke;
}
}
public class JavaDyProxy {
public static void main(String[] args) {
ITest test = new Test();
final ITest o = (ITest) Proxy.newProxyInstance(ITest.class.getClassLoader()
, new Class>[]{ITest.class}, new Invocation(test));
o.a();
}
}
如下代码生成代理对象class文件。
private static void saveProxyFile() {
FileOutputStream out = null;
try {
byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", Test.class.getInterfaces());
out = new FileOutputStream( "D:/$Proxy0.class");
out.write(classFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
通过idea打开查看class文件代码。
public final class $Proxy0 extends Proxy implements ITest {
private static Method m1;
private static Method m3;
private static Method m4;
private static Method m2;
private static Method m0;
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
try {
\\h对象,都是InvocationHandler类的实例
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 b() throws {
try {
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
public final void a() throws {
try {
super.h.invoke(this, m4, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
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.example.proxy.ITest").getMethod("b");
m4 = Class.forName("com.example.proxy.ITest").getMethod("a");
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());
}
}
}
代理类$Proxy0,继承Proxy类也实现ITest类。
CGLib
先来一段代码
class TestCg{
public void a() {
System.out.println("***************");
// 1
System.out.println(this);
System.out.println("***************");
System.out.println("------a");
b();
}
public void b() {
System.out.println("-------b");
}
}
class MyMethodInterceptor implements MethodInterceptor{
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("before method run..."+method);
// 2 o是代理后的子类 ,method是调用方法 ,objects是方法入参 , methodProxy是MethodProxy代理对象
return methodProxy.invokeSuper(o,objects);
}
}
public class CgLib {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(TestCg.class);
enhancer.setCallback(new MyMethodInterceptor());
final TestCg o = (TestCg) enhancer.create();
o.a();
}
}
打印结果:
before method run...public void com.example.proxy.TestCg.a()
***************
before method run...public java.lang.String java.lang.Object.toString()
before method run...public native int java.lang.Object.hashCode()
// 1
com.example.proxy.TestCg$$EnhancerByCGLIB$$195b34d1@3b22cdd0
***************
------a
before method run...public void com.example.proxy.TestCg.b()
-------b
在上述代码中标注中
- 标注1处,可以看出this表示打印结果标注1处('TestCg$$EnhancerByCGLIB'),是Test的增强类。我们可以知道,a方法中调用b方法,b方法可以增强。(疑问Spring AOP 使用cglib为何没有增强,卖个关子)。
- 标注2处,invokeSuper传入参数是CGLib代理子类,就相当于使用了TestCg$$EnhancerByCGLIB这个子类的b方法。
我们稍作代码调整
class TestCg{
public void a() {
System.out.println("***************");
System.out.println(this);
System.out.println("***************");
System.out.println("------a");
b();
}
public void b() {
System.out.println("-------b");
}
}
class MyMethodInterceptor implements MethodInterceptor{
//1
private Object target;
public MyMethodInterceptor(Object target) {
super();
this.target = target;
}
//1
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("before method run..."+method);
//2 return methodProxy.invokeSuper(o,objects);
return methodProxy.invoke(target,objects);
}
}
public class CgLib {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(TestCg.class);
enhancer.setCallback(new MyMethodInterceptor(new TestCg()));
final TestCg o = (TestCg) enhancer.create();
o.a();
}
}
标注1和2代码做调整,我们看看打印数据。
before method run...public void com.example.proxy.a.TestCg.a()
***************
//1
com.example.proxy.a.TestCg@3b22cdd0
***************
------a
-------b
打印数据可以看出,我们调用b方法没有得到增强,打印标注1处为TestCg@3b22cdd0,我们普通对象。Spring AOP调用的是methodProxy.invoke(target,objects),我们都可以知道,同一类的方法a(默认事务),b(事务传递性开启新事务),他们开启不同事务,b不会创建新事务。invoke方法调用为增强,invokeSuper方法增强。
接下来源码分析,首先上一张图。
//获取cglib生成的三个class文件
//1 TestCg$$EnhancerByCGLIB$$195b34d1.class
//2 TestCg$$EnhancerByCGLIB$$195b34d1$$FastClassByCGLIB$$9de9bc2.class
//3 TestCg$$FastClassByCGLIB$$a0acbc87.class
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\api");
代码很多,考虑到以后查看方便,可读性差,大家可以看看我标注即可。
package com.example.proxy;
import java.lang.reflect.Method;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class TestCg$$EnhancerByCGLIB$$195b34d1 extends TestCg implements Factory {
private boolean CGLIB$BOUND;
private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
private static final Callback[] CGLIB$STATIC_CALLBACKS;
//拦截器
private MethodInterceptor CGLIB$CALLBACK_0;
//被代理方法
private static final Method CGLIB$b$0$Method;
//代理方法
private static final MethodProxy CGLIB$b$0$Proxy;
private static final Object[] CGLIB$emptyArgs;
private static final Method CGLIB$a$1$Method;
private static final MethodProxy CGLIB$a$1$Proxy;
private static final Method CGLIB$finalize$2$Method;
private static final MethodProxy CGLIB$finalize$2$Proxy;
private static final Method CGLIB$equals$3$Method;
private static final MethodProxy CGLIB$equals$3$Proxy;
private static final Method CGLIB$toString$4$Method;
private static final MethodProxy CGLIB$toString$4$Proxy;
private static final Method CGLIB$hashCode$5$Method;
private static final MethodProxy CGLIB$hashCode$5$Proxy;
private static final Method CGLIB$clone$6$Method;
private static final MethodProxy CGLIB$clone$6$Proxy;
static void CGLIB$STATICHOOK1() {
CGLIB$THREAD_CALLBACKS = new ThreadLocal();
CGLIB$emptyArgs = new Object[0];
//代理类
Class var0 = Class.forName("com.example.proxy.TestCg$$EnhancerByCGLIB$$195b34d1");
// 被代理类
Class var1;
Method[] var10000 = ReflectUtils.findMethods(new String[]{"finalize", "()V", "equals", "(Ljava/lang/Object;)Z", "toString", "()Ljava/lang/String;", "hashCode", "()I", "clone", "()Ljava/lang/Object;"}, (var1 = Class.forName("java.lang.Object")).getDeclaredMethods());
CGLIB$finalize$2$Method = var10000[0];
CGLIB$finalize$2$Proxy = MethodProxy.create(var1, var0, "()V", "finalize", "CGLIB$finalize$2");
CGLIB$equals$3$Method = var10000[1];
CGLIB$equals$3$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$3");
CGLIB$toString$4$Method = var10000[2];
CGLIB$toString$4$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "toString", "CGLIB$toString$4");
CGLIB$hashCode$5$Method = var10000[3];
CGLIB$hashCode$5$Proxy = MethodProxy.create(var1, var0, "()I", "hashCode", "CGLIB$hashCode$5");
CGLIB$clone$6$Method = var10000[4];
CGLIB$clone$6$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/Object;", "clone", "CGLIB$clone$6");
//此处为被代理类赋值
var10000 = ReflectUtils.findMethods(new String[]{"b", "()V", "a", "()V"}, (var1 = Class.forName("com.example.proxy.TestCg")).getDeclaredMethods());
CGLIB$b$0$Method = var10000[0];
CGLIB$b$0$Proxy = MethodProxy.create(var1, var0, "()V", "b", "CGLIB$b$0");
CGLIB$a$1$Method = var10000[1];
CGLIB$a$1$Proxy = MethodProxy.create(var1, var0, "()V", "a", "CGLIB$a$1");
}
final void CGLIB$b$0() {
super.b();
}
public final void b() {
MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
if (var10000 == null) {
CGLIB$BIND_CALLBACKS(this);
var10000 = this.CGLIB$CALLBACK_0;
}
if (var10000 != null) {
var10000.intercept(this, CGLIB$b$0$Method, CGLIB$emptyArgs, CGLIB$b$0$Proxy);
} else {
super.b();
}
}
//代理方法,methodProxy.invokeSuper 时候调用
final void CGLIB$a$1() {
super.a();
}
//被代理方法,methodProxy.invoke 调用,死循环这里产生
public final void a() {
MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
if (var10000 == null) {
CGLIB$BIND_CALLBACKS(this);
var10000 = this.CGLIB$CALLBACK_0;
}
if (var10000 != null) {
var10000.intercept(this, CGLIB$a$1$Method, CGLIB$emptyArgs, CGLIB$a$1$Proxy);
} else {
super.a();
}
}
final void CGLIB$finalize$2() throws Throwable {
super.finalize();
}
protected final void finalize() throws Throwable {
MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
if (var10000 == null) {
CGLIB$BIND_CALLBACKS(this);
var10000 = this.CGLIB$CALLBACK_0;
}
if (var10000 != null) {
var10000.intercept(this, CGLIB$finalize$2$Method, CGLIB$emptyArgs, CGLIB$finalize$2$Proxy);
} else {
super.finalize();
}
}
final boolean CGLIB$equals$3(Object var1) {
return super.equals(var1);
}
public final boolean equals(Object var1) {
MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
if (var10000 == null) {
CGLIB$BIND_CALLBACKS(this);
var10000 = this.CGLIB$CALLBACK_0;
}
if (var10000 != null) {
Object var2 = var10000.intercept(this, CGLIB$equals$3$Method, new Object[]{var1}, CGLIB$equals$3$Proxy);
return var2 == null ? false : (Boolean)var2;
} else {
return super.equals(var1);
}
}
final String CGLIB$toString$4() {
return super.toString();
}
public final String toString() {
MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
if (var10000 == null) {
CGLIB$BIND_CALLBACKS(this);
var10000 = this.CGLIB$CALLBACK_0;
}
return var10000 != null ? (String)var10000.intercept(this, CGLIB$toString$4$Method, CGLIB$emptyArgs, CGLIB$toString$4$Proxy) : super.toString();
}
final int CGLIB$hashCode$5() {
return super.hashCode();
}
public final int hashCode() {
MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
if (var10000 == null) {
CGLIB$BIND_CALLBACKS(this);
var10000 = this.CGLIB$CALLBACK_0;
}
if (var10000 != null) {
Object var1 = var10000.intercept(this, CGLIB$hashCode$5$Method, CGLIB$emptyArgs, CGLIB$hashCode$5$Proxy);
return var1 == null ? 0 : ((Number)var1).intValue();
} else {
return super.hashCode();
}
}
final Object CGLIB$clone$6() throws CloneNotSupportedException {
return super.clone();
}
protected final Object clone() throws CloneNotSupportedException {
MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
if (var10000 == null) {
CGLIB$BIND_CALLBACKS(this);
var10000 = this.CGLIB$CALLBACK_0;
}
return var10000 != null ? var10000.intercept(this, CGLIB$clone$6$Method, CGLIB$emptyArgs, CGLIB$clone$6$Proxy) : super.clone();
}
public static MethodProxy CGLIB$findMethodProxy(Signature var0) {
String var10000 = var0.toString();
switch(var10000.hashCode()) {
case -1574182249:
if (var10000.equals("finalize()V")) {
return CGLIB$finalize$2$Proxy;
}
break;
case -508378822:
if (var10000.equals("clone()Ljava/lang/Object;")) {
return CGLIB$clone$6$Proxy;
}
break;
case 2929524:
if (var10000.equals("a()V")) {
return CGLIB$a$1$Proxy;
}
break;
case 2959315:
if (var10000.equals("b()V")) {
return CGLIB$b$0$Proxy;
}
break;
case 1826985398:
if (var10000.equals("equals(Ljava/lang/Object;)Z")) {
return CGLIB$equals$3$Proxy;
}
break;
case 1913648695:
if (var10000.equals("toString()Ljava/lang/String;")) {
return CGLIB$toString$4$Proxy;
}
break;
case 1984935277:
if (var10000.equals("hashCode()I")) {
return CGLIB$hashCode$5$Proxy;
}
}
return null;
}
public TestCg$$EnhancerByCGLIB$$195b34d1() {
CGLIB$BIND_CALLBACKS(this);
}
public static void CGLIB$SET_THREAD_CALLBACKS(Callback[] var0) {
CGLIB$THREAD_CALLBACKS.set(var0);
}
public static void CGLIB$SET_STATIC_CALLBACKS(Callback[] var0) {
CGLIB$STATIC_CALLBACKS = var0;
}
private static final void CGLIB$BIND_CALLBACKS(Object var0) {
TestCg$$EnhancerByCGLIB$$195b34d1 var1 = (TestCg$$EnhancerByCGLIB$$195b34d1)var0;
if (!var1.CGLIB$BOUND) {
var1.CGLIB$BOUND = true;
Object var10000 = CGLIB$THREAD_CALLBACKS.get();
if (var10000 == null) {
var10000 = CGLIB$STATIC_CALLBACKS;
if (var10000 == null) {
return;
}
}
var1.CGLIB$CALLBACK_0 = (MethodInterceptor)((Callback[])var10000)[0];
}
}
public Object newInstance(Callback[] var1) {
CGLIB$SET_THREAD_CALLBACKS(var1);
TestCg$$EnhancerByCGLIB$$195b34d1 var10000 = new TestCg$$EnhancerByCGLIB$$195b34d1();
CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
return var10000;
}
public Object newInstance(Callback var1) {
CGLIB$SET_THREAD_CALLBACKS(new Callback[]{var1});
TestCg$$EnhancerByCGLIB$$195b34d1 var10000 = new TestCg$$EnhancerByCGLIB$$195b34d1();
CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
return var10000;
}
public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
CGLIB$SET_THREAD_CALLBACKS(var3);
TestCg$$EnhancerByCGLIB$$195b34d1 var10000 = new TestCg$$EnhancerByCGLIB$$195b34d1;
switch(var1.length) {
case 0:
var10000.();
CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
return var10000;
default:
throw new IllegalArgumentException("Constructor not found");
}
}
public Callback getCallback(int var1) {
CGLIB$BIND_CALLBACKS(this);
MethodInterceptor var10000;
switch(var1) {
case 0:
var10000 = this.CGLIB$CALLBACK_0;
break;
default:
var10000 = null;
}
return var10000;
}
public void setCallback(int var1, Callback var2) {
switch(var1) {
case 0:
this.CGLIB$CALLBACK_0 = (MethodInterceptor)var2;
default:
}
}
public Callback[] getCallbacks() {
CGLIB$BIND_CALLBACKS(this);
return new Callback[]{this.CGLIB$CALLBACK_0};
}
public void setCallbacks(Callback[] var1) {
this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
}
static {
CGLIB$STATICHOOK1();
}
}
MethodProxy源码
public class MethodProxy {
private Signature sig1;
private Signature sig2;
private MethodProxy.CreateInfo createInfo;
private final Object initLock = new Object();
private volatile MethodProxy.FastClassInfo fastClassInfo;
//c1 被代理类
//c2 代理类
//name1 被代理方法
//name12 代理方法
public static MethodProxy create(Class c1, Class c2, String desc, String name1, String name2) {
MethodProxy proxy = new MethodProxy();
proxy.sig1 = new Signature(name1, desc);
proxy.sig2 = new Signature(name2, desc);
proxy.createInfo = new MethodProxy.CreateInfo(c1, c2);
return proxy;
}
private void init() {
if (this.fastClassInfo == null) {
synchronized(this.initLock) {
if (this.fastClassInfo == null) {
MethodProxy.CreateInfo ci = this.createInfo;
MethodProxy.FastClassInfo fci = new MethodProxy.FastClassInfo();
fci.f1 = helper(ci, ci.c1);
fci.f2 = helper(ci, ci.c2);
//获取被代理方法标识
fci.i1 = fci.f1.getIndex(this.sig1);
//获取代理方法标识
fci.i2 = fci.f2.getIndex(this.sig2);
this.fastClassInfo = fci;
this.createInfo = null;
}
}
}
}
}
继承FastClass代理类,下面省略了大量代码。
public class TestCg$$EnhancerByCGLIB$$195b34d1$$FastClassByCGLIB$$9de9bc2 extends FastClass {
public TestCg$$EnhancerByCGLIB$$195b34d1$$FastClassByCGLIB$$9de9bc2(Class var1) {
super(var1);
}
//获取调用方法标志
public int getIndex(Signature var1) {
String var10000 = var1.toString();
switch(var10000.hashCode()) {
case -62700918:
if (var10000.equals("CGLIB$a$1()V")) {
return 16;
}
break;
case -34101558:
if (var10000.equals("CGLIB$b$0()V")) {
return 17;
}
break;
case 2929524:
if (var10000.equals("a()V")) {
return 8;
}
break;
case 2959315:
if (var10000.equals("b()V")) {
return 6;
}
break;
return -1;
}
public Object invoke(int var1, Object var2, Object[] var3) throws InvocationTargetException {
195b34d1 var10000 = (195b34d1)var2;
int var10001 = var1;
try {
switch(var10001) {
case 6:
var10000.b();
return null;
case 8:
var10000.a();
return null;
//上下方法都是调用代理类方法。
case 16:
var10000.CGLIB$a$1();
return null;
case 17:
var10000.CGLIB$b$0();
return null;
}
} catch (Throwable var4) {
throw new InvocationTargetException(var4);
}
throw new IllegalArgumentException("Cannot find matching method/constructor");
}
}
分析被代理类源码
public class TestCg$$FastClassByCGLIB$$a0acbc87 extends FastClass {
public TestCg$$FastClassByCGLIB$$a0acbc87(Class var1) {
super(var1);
}
public int getIndex(Signature var1) {
String var10000 = var1.toString();
switch(var10000.hashCode()) {
case 2929524:
if (var10000.equals("a()V")) {
return 1;
}
break;
case 2959315:
if (var10000.equals("b()V")) {
return 0;
}
break;
return -1;
}
public Object invoke(int var1, Object var2, Object[] var3) throws InvocationTargetException {
TestCg var10000 = (TestCg)var2;
int var10001 = var1;
try {
switch(var10001) {
case 0:
var10000.b();
return null;
case 1:
//此类
var10000.a();
return null;
}
} catch (Throwable var4) {
throw new InvocationTargetException(var4);
}
throw new IllegalArgumentException("Cannot find matching method/constructor");
}
public Object newInstance(int var1, Object[] var2) throws InvocationTargetException {
TestCg var10000 = new TestCg;
TestCg var10001 = var10000;
int var10002 = var1;
try {
switch(var10002) {
case 0:
var10001.();
return var10000;
}
} catch (Throwable var3) {
throw new InvocationTargetException(var3);
}
}
}
JDK动态代理和Cglib区别
- JDK动态代理实现对象接口,Cglib是继承被代理对象。
- JDK和Cglib运行时候生成字节码,Cglib生成效率低下。
- JDK用反射机制执行方法,Cglib通过FastClass机制直接调用方法,效率高。
参考文献:
Cglib invoke以及invokeSuper的一点区别
Java两种动态代理JDK动态代理和CGLIB动态代理
Spring 如何在一个事务中开启另一个事务
Cglib动态代理实现方式