通用准备
public interface IStudentService {
void save(String username);
}
public class StudentService implements IStudentService {
@Override
public void save(String username) {
System.out.println("save student");
}
}
JDK动态代理
限制
限制:要代理的对象必须有接口
自定义 InvocationHandler
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class StudentInvocationHandler implements InvocationHandler {
private final Object targetObject;
private final static String METHOD_SAVE = "save";
public StudentInvocationHandler(Object targetObject) {
this.targetObject = targetObject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (METHOD_SAVE.equals(method.getName())) {
System.out.println("before save");
Object result = method.invoke(targetObject, args);
System.out.println("after save");
return result;
}
else {
return method.invoke(targetObject, args);
}
}
}
使用:
package com.hdu.jdk;
import com.hdu.IStudentService;
import com.hdu.StudentService;
import sun.misc.ProxyGenerator;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
StudentInvocationHandler studentInvocationHandler = new StudentInvocationHandler(new StudentService());
IStudentService studentService = (IStudentService) Proxy.newProxyInstance(
StudentService.class.getClassLoader(),
new Class[]{IStudentService.class},
studentInvocationHandler
);
studentService.save("张三");
//before save
//save student
//after save
}
}
原理讲解:
可以先保存一下 看生成的代理类长什么样子
private static void getProxySourceCode() throws FileNotFoundException {
byte[] $Proxy0s = ProxyGenerator.generateProxyClass("$Proxy0", StudentService.class.getInterfaces());
FileOutputStream fileOutputStream = new FileOutputStream(
"D:\\$Proxy0.class"
);
try {
fileOutputStream.write($Proxy0s);
} catch (IOException e) {
}
}
$Proxy0
package com.hdu.jdk;//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
import com.hdu.IStudentService;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class $Proxy0 extends Proxy implements IStudentService {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public $Proxy0(InvocationHandler var1) {
super(var1);
}
public final boolean equals(Object var1) {
try {
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 save(String var1) {
try {
super.h.invoke(this, m3, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
public final String toString() {
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() {
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.hdu.IStudentService").getMethod("save", Class.forName("java.lang.String"));
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());
}
}
}
重点观察save方法,其实就是调用 代理类的 save方法的时候会回调我们写的 StudentInvocationHandler,回调的 StudentInvocationHandler 里面写了增强逻辑。
其实 Proxy0 的代码是模板性的,我们可以通过拼接字符串的方式拼接出 $Proxy0 类的内容,然后将他生成为 class文件,加载到JVM内存,这就是一个简单的实现动态代理的方式。
Cglib动态代理
限制:
他的限制不需要被增强的类必须有一个接口,但是他需要满足 被增强的方法不能是 final 修饰
自定义 CglibInterceptor
package com.hdu.cglib;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibInterceptor implements MethodInterceptor {
Object targetObject;
public CglibInterceptor(Object targetObject) {
this.targetObject = targetObject;
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("前置增强");
Object res = methodProxy.invokeSuper(o, objects);
System.out.println("后置增强");
return res;
}
}
使用:
public class Main {
public static void main(String[] args) {
// 这句代码的意思是将生成的代理类的字节码文件写入到指定的目录下
System.setProperty(
DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,
"D:\\cglib_proxy"
);
CglibInterceptor cglibInterceptor = new CglibInterceptor(new StudentService());
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(StudentService.class);
enhancer.setCallback(cglibInterceptor);
IStudentService studentService = (StudentService) enhancer.create();
studentService.save("张三");
}
}
原理讲解:
StudentServiceEnhancerByCGLIB$$85475f6e
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.hdu.cglib;
import java.lang.reflect.Method;
import com.hdu.StudentService;
import net.sf.cglib.core.ReflectUtils;
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 StudentService$$EnhancerByCGLIB$$85475f6e extends StudentService 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$save$0$Method;
private static final MethodProxy CGLIB$save$0$Proxy;
private static final Object[] CGLIB$emptyArgs;
private static final Method CGLIB$finalize$1$Method;
private static final MethodProxy CGLIB$finalize$1$Proxy;
private static final Method CGLIB$equals$2$Method;
private static final MethodProxy CGLIB$equals$2$Proxy;
private static final Method CGLIB$toString$3$Method;
private static final MethodProxy CGLIB$toString$3$Proxy;
private static final Method CGLIB$hashCode$4$Method;
private static final MethodProxy CGLIB$hashCode$4$Proxy;
private static final Method CGLIB$clone$5$Method;
private static final MethodProxy CGLIB$clone$5$Proxy;
static void CGLIB$STATICHOOK1() {
CGLIB$THREAD_CALLBACKS = new ThreadLocal();
CGLIB$emptyArgs = new Object[0];
Class var0 = Class.forName("com.hdu.StudentService$$EnhancerByCGLIB$$85475f6e");
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$1$Method = var10000[0];
CGLIB$finalize$1$Proxy = MethodProxy.create(var1, var0, "()V", "finalize", "CGLIB$finalize$1");
CGLIB$equals$2$Method = var10000[1];
CGLIB$equals$2$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$2");
CGLIB$toString$3$Method = var10000[2];
CGLIB$toString$3$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "toString", "CGLIB$toString$3");
CGLIB$hashCode$4$Method = var10000[3];
CGLIB$hashCode$4$Proxy = MethodProxy.create(var1, var0, "()I", "hashCode", "CGLIB$hashCode$4");
CGLIB$clone$5$Method = var10000[4];
CGLIB$clone$5$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/Object;", "clone", "CGLIB$clone$5");
CGLIB$save$0$Method = ReflectUtils.findMethods(new String[]{"save", "(Ljava/lang/String;)V"}, (var1 = Class.forName("com.hdu.StudentService")).getDeclaredMethods())[0];
CGLIB$save$0$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/String;)V", "save", "CGLIB$save$0");
}
public final void save(String var1) {
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$save$0$Method, new Object[]{var1}, CGLIB$save$0$Proxy);
} else {
super.save(var1);
}
}
}
同样 当调用 StudentServiceEnhancerByCGLIB$$85475f6e 的 save方法之后 会回调到我们的自定义 CglibInterceptor,自定义 CglibInterceptor 的拦截方法进行了增强。
具体的实习原理和 JDK动态代理差不多,这里不再叙述