JDK动态代理
JDK动态代理是代理模式的一种实现方式。只能代理接口类,因为Java语言为单继承语言,所以只能以实现接口的方式构建代理对象。
简单示例
package com.chinda.aop;
/**
* 被代理接口
*
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public interface Subject {
void doSomething();
}
package com.chinda.aop;
/**
* 真正的对象
*
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public class RealSubject implements Subject {
@Override
public void doSomething() {
System.out.println("realSubject to do something!");
}
}
import com.chinda.aop.RealSubject;
import com.chinda.aop.Subject;
import org.junit.Test;
import java.lang.reflect.Proxy;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public class JdkDynamicProxyTest {
@Test
public void test() {
// 保存生成的代理类的字节码文件, 方便查看(可省略)
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
RealSubject realSubject = new RealSubject();
Subject subjectProxy = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), (proxy, method, args) -> {
System.out.println("before to do something!");
Object result = method.invoke(realSubject, args);
System.out.println("after to do something!");
return result;
});
subjectProxy.doSomething();
}
}
控制台输出
before to do something!
realSubject to do something!
after to do something!
注意: 保存代理类字节码文件需要配置jvm参数:-Dsun.misc.ProxyGenerator.saveGeneratedFiles=true
代理类字节码文件反编译
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.sun.proxy;
import com.chinda.aop.Subject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class $Proxy4 extends Proxy implements Subject {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public $Proxy4(InvocationHandler var1) throws {
super(var1);
}
public final boolean equals(Object var1) throws {
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 doSomething() throws {
try {
super.h.invoke(this, m3, (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.chinda.aop.Subject").getMethod("doSomething");
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());
}
}
}
-
代理类继承了Proxy类并且实现了要代理的接口,由于java不支持多继承,所以JDK动态代理不能代理类。
-
重写了equals、hashCode、toString。
-
有一个静态代码块,通过反射或者代理类的所有方法。
-
通过invoke执行代理类中的目标方法doSomething。
源码分析
jdk版本
$ java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
粗略流程
- 生成代理类字节文件,继承Proxy并实现被代理接口。
- 用加载被代理接口的ClassLoader将代理类字节码文件加载到虚拟机中,创建代理对象。
- 执行目标对象的目标方法。
查看Proxy.newProxyInstance
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
// 检查调用控制器是否为null, 若是null抛异常
Objects.requireNonNull(h);
// 克隆接口Class[]
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// 检查代理是否可以创建
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* Look up or generate the designated proxy class.
* 生成接口代理类的字节码文件
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* 使用自定义的InvocationHandler构造代理对象实例
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
查看创建代理类字节码文件getProxyClass0
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
// 判断接口数是否超过65535
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// 如果缓存中已经存在相应接口的代理类,直接返回;否则,使用ProxyClassFactory创建代理类
return proxyClassCache.get(loader, interfaces);
}
查看proxyClassCache.get(loader, interfaces)
// 创建代理类
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
查看ProxyClassFactory
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// 代理类名称前缀
private static final String proxyClassNamePrefix = "$Proxy";
// 下一个代理类名称后缀:比如$Proxy0.class、$Proxy1.class
private static final AtomicLong nextUniqueNumber = new AtomicLong();
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
// 校验类加载器是否能通过接口名称加载该类
Class<?> interfaceClass = null;
try {
interfaceClass = Class.forName(intf.getName(), false, loader);
} catch (ClassNotFoundException e) {
}
if (interfaceClass != intf) {
throw new IllegalArgumentException(
intf + " is not visible from class loader");
}
// 校验代理类是否是接口
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* 校验接口是否重复
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // package to define proxy class in
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
for (Class<?> intf : interfaces) {
int flags = intf.getModifiers();
if (!Modifier.isPublic(flags)) {
accessFlags = Modifier.FINAL;
String name = intf.getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
} else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}
if (proxyPkg == null) {
// 构建代理类包名
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* 生成指定的代理类字节流
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
// 加载字节流文件
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
throw new IllegalArgumentException(e.toString());
}
}
}
封装上述示例
接口,实现类保持不变。
引入依赖包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
创建动态代理功能类
package com.chinda.aop;
import lombok.AllArgsConstructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
@AllArgsConstructor
public class JdkDynamicProxy implements InvocationHandler {
/**
* 被代理类
*/
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
System.out.println("before to do something!");
result = method.invoke(target, args);
System.out.println("return to do something! result: " + result);
} catch (Exception e) {
e.printStackTrace();
System.out.println("exception to do something");
} finally {
System.out.println("after to do something!");
}
return result;
}
}
创建测试方法
import com.chinda.aop.JdkDynamicProxy;
import com.chinda.aop.RealSubject;
import com.chinda.aop.Subject;
import org.junit.Test;
import java.lang.reflect.Proxy;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public class JdkDynamicProxyTest {
@Test
public void test2() {
RealSubject realSubject = new RealSubject();
Subject subjectProxy = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), new JdkDynamicProxy(realSubject));
subjectProxy.doSomething();
}
}
继续封装
创建获取代理接口
package com.chinda.aop;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public interface AopProxy {
/**
* 获取代理类
* @return
*/
Object getProxy();
}
修改动态代理功能类
package com.chinda.aop;
import lombok.AllArgsConstructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
@AllArgsConstructor
public class JdkDynamicProxy implements AopProxy, InvocationHandler {
/**
* 被代理类
*/
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
System.out.println("before to do something!");
result = method.invoke(target, args);
System.out.println("return to do something! result: " + result);
} catch (Exception e) {
e.printStackTrace();
System.out.println("exception to do something");
} finally {
System.out.println("after to do something!");
}
return result;
}
@Override
public Object getProxy() {
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
}
创建测试方法
import com.chinda.aop.JdkDynamicProxy;
import com.chinda.aop.RealSubject;
import com.chinda.aop.Subject;
import org.junit.Test;
import java.lang.reflect.Proxy;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
public class JdkDynamicProxyTest {
@Test
public void test3() {
Subject subjectProxy = (Subject) new JdkDynamicProxy(new RealSubject()).getProxy();
subjectProxy.doSomething();
}
}
继续封装
引入依赖
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
创建方法拦截器链【通知(Advice)】
前置通知,异常通知,返回通知等可以在这里实现。
package com.chinda.aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* @author Wang Chinda
* @date 2020/5/15
* @see
* @since 1.0
*/
public class TimerInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
long time = System.nanoTime();
System.out.println("Invocation of Method " + invocation.getMethod().getName() + " start!");
Object proceed = invocation.proceed();
System.out.println("Invocation of Method " + invocation.getMethod().getName() + " end! takes " + (System.nanoTime() - time)
+ " nanoseconds.");
return proceed;
}
}
创建代理方法调用【连接点(Joinpoint)】
package com.chinda.aop;
import lombok.AllArgsConstructor;
import org.aopalliance.intercept.MethodInvocation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
@AllArgsConstructor
public class ReflectiveMethodInvocation implements MethodInvocation {
private Object target;
private Method method;
private Object[] args;
@Override
public Method getMethod() {
return this.method;
}
@Override
public Object[] getArguments() {
return this.args;
}
@Override
public Object proceed() throws Throwable {
return this.method.invoke(this.target, this.args);
}
@Override
public Object getThis() {
return this.target;
}
@Override
public AccessibleObject getStaticPart() {
return this.method;
}
}
修改动态代理功能类
package com.chinda.aop;
import com.chinda.aop.interceptor.TimerInterceptor;
import lombok.AllArgsConstructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author Wang Chinda
* @date 2020/5/16
* @see
* @since 1.0
*/
@AllArgsConstructor
public class JdkDynamicProxy implements AopProxy, InvocationHandler {
/**
* 被代理类
*/
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
TimerInterceptor timerInterceptor = new TimerInterceptor();
return timerInterceptor.invoke(new ReflectiveMethodInvocation(target, method, args));
}
@Override
public Object getProxy() {
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
}