Java動態(tài)代理
代理是對某個對象入录,在調(diào)用方法前后做事情来涨。靜態(tài)代理對某個給定對象做代理,動態(tài)代理是給定的對象不確定梅割。這里主要講的是動態(tài)代理霜第,下面是實現(xiàn)源碼。
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類也實現(xiàn)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是調(diào)用方法 无切,objects是方法入?yún)?泳秀, 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();
}
}
打印結(jié)果:
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表示打印結(jié)果標注1處('TestCg$$EnhancerByCGLIB')朱沃,是Test的增強類晴玖。我們可以知道,a方法中調(diào)用b方法为流,b方法可以增強呕屎。(疑問Spring AOP 使用cglib為何沒有增強,賣個關(guān)子)敬察。
- 標注2處秀睛,invokeSuper傳入?yún)?shù)是CGLib代理子類,就相當于使用了TestCg$$EnhancerByCGLIB這個子類的b方法莲祸。
我們稍作代碼調(diào)整
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代碼做調(diào)整蹂安,我們看看打印數(shù)據(jù)椭迎。
before method run...public void com.example.proxy.a.TestCg.a()
***************
//1
com.example.proxy.a.TestCg@3b22cdd0
***************
------a
-------b
打印數(shù)據(jù)可以看出,我們調(diào)用b方法沒有得到增強,打印標注1處為TestCg@3b22cdd0田盈,我們普通對象畜号。Spring AOP調(diào)用的是methodProxy.invoke(target,objects),我們都可以知道允瞧,同一類的方法a(默認事務(wù)),b(事務(wù)傳遞性開啟新事務(wù))简软,他們開啟不同事務(wù),b不會創(chuàng)建新事務(wù)述暂。invoke方法調(diào)用為增強痹升,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 時候調(diào)用
final void CGLIB$a$1() {
super.a();
}
//被代理方法绳锅,methodProxy.invoke 調(diào)用,死循環(huán)這里產(chǎn)生
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.<init>();
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);
}
//獲取調(diào)用方法標志
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;
//上下方法都是調(diào)用代理類方法。
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.<init>();
return var10000;
}
} catch (Throwable var3) {
throw new InvocationTargetException(var3);
}
}
}
JDK動態(tài)代理和Cglib區(qū)別
- JDK動態(tài)代理實現(xiàn)對象接口期虾,Cglib是繼承被代理對象原朝。
- JDK和Cglib運行時候生成字節(jié)碼,Cglib生成效率低下镶苞。
- JDK用反射機制執(zhí)行方法喳坠,Cglib通過FastClass機制直接調(diào)用方法,效率高茂蚓。
參考文獻:
Cglib invoke以及invokeSuper的一點區(qū)別
Java兩種動態(tài)代理JDK動態(tài)代理和CGLIB動態(tài)代理
Spring 如何在一個事務(wù)中開啟另一個事務(wù)
Cglib動態(tài)代理實現(xiàn)方式