特点
动态代理是AOP的核心技术,JDK的动态代理主要基于java.lang.reflect.InvocationHandler
与java.lang.reflect.Proxy
类,通过反射技术创建代理对象。
实现
创建一个@Before
注解,在Sales
接口上加上注解
public interface Sales {
@Before
void sale(Goods goods);
}
创建一个InvocationHandler
,实现invoke
方法
@Slf4j
public class ProxyHandler implements InvocationHandler {
private Sales target;
public ProxyHandler(Sales target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
beforeInvoke(method);
Object invoke = method.invoke(this.target, args);
return invoke;
}
// 调用方法前的处理,当方法上能获取到Before注解时,对原始对象再次代理,加入加价逻辑
private void beforeInvoke(Method method) {
Before annotation = method.getAnnotation(Before.class);
if (annotation != null){
this.target = new RestProxy(target);
}
}
}
测试代码
@Test
public void testJDKProxy(){
Goods goods = new Goods();
Sales factory = new Factory();
ProxyHandler proxyHandler = new ProxyHandler(factory);
Object proxyInstance = Proxy.newProxyInstance(factory.getClass().getClassLoader(), new Class[]{Sales.class}, proxyHandler);
Sales proxy = (Sales) proxyInstance;
proxy.sale(goods);
}
日志信息
2021-03-26 14:29:46.079 INFO 11576 --- [ main] org.example.proxy.rest.RestProxy : 商品加价前: Goods(super=org.example.proxy.core.Goods@d215c1e, price=1200.00, name=手机)
2021-03-26 14:29:46.081 INFO 11576 --- [ main] org.example.proxy.rest.RestProxy : 商品加价后: Goods(super=org.example.proxy.core.Goods@1294c6ae, price=1700.00, name=手机)
2021-03-26 14:29:46.081 INFO 11576 --- [ main] org.example.proxy.rest.Factory : 商品最终价格: Goods(super=org.example.proxy.core.Goods@1294c6ae, price=1700.00, name=手机)
原理及源码跟踪
从Proxy
类的方法进去查看代码:一通验证之后,首先执行了getProxyClass0
,然后获取构造方法,并将构造方法设置为可访问,最后通过反射创建实例。
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
// 验证InvocationHandler不能为空
Objects.requireNonNull(h);
// 克隆复制接口
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);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
// 获取构造方法
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
// 判断构造方法是不是public类型,若不是设置为允许操作
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
可知,最终的类是从proxyClassCache
缓存中获取:
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
// 判断接口数组的长度 不能大于 65535个
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// If the proxy class defined by the given loader implementing
// the given interfaces exists, this will simply return the cached copy;
// otherwise, it will create the proxy class via the ProxyClassFactory
// 从缓存中获取代理类
return proxyClassCache.get(loader, interfaces);
}
查看proxyClassCache
对象被声明的代码,创建了一个WeakCache
,并传递进去了KeyFactory
和ProxyClassFactory
对象,这两个类都是Proxy
类的内部类,前者创建了代理类在缓存中的key
,后者主要是代理类的生成过程:
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
查看ProxyClassFactory
代码,经过一系列的检查,设置完成代理类名称,然后调用ProxyGenerator.generateProxyClass()
方法生成字节码,最后调用defineClass0
方法生成类,defineClass0
为native
方法,主要查看ProxyGenerator.generateProxyClass()
方法;
/**
* A factory function that generates, defines and returns the proxy class given
* the ClassLoader and array of interfaces.
*/
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// prefix for all proxy class names
// 定义生成的代理类名称前缀
private static final String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class names
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) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
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");
}
/*
* Verify that the Class object actually represents an
* interface.
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
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;
/*
* Record the package of a non-public proxy interface so that the
* proxy class will be defined in the same package. Verify that
* all non-public proxy interfaces are in the same package.
*/
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) {
// if no non-public proxy interfaces, use com.sun.proxy package
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
/*
* Choose a name for the proxy class to generate.
* 获取生成代理类名称=包名+前缀+nextUniqueNumber.getAndIncrement()
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
*/
// 生成字节流 核心方法
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
// 调用native方法生成类
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
}
查看ProxyGenerator
类中的generateProxyClass
方法,该方法有3个参数,参数1是代理类名称、参数2是接口类、参数3是Modifier
类中16进制数字,该方法先是创建了一个ProxyGenerator
对象,将3个参数通过构造方法初始化对象中属性值,然后调用generateClassFile()
方法生成字节数组,最后通过saveGeneratedFiles
属性判断是否需要生成代理文件。generateClassFile()
方法将 hashCode
,equals
,toString
都默认加入到代理类实现中;
public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
// 创建对象
ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
// 生成字节码
final byte[] var4 = var3.generateClassFile();
if (saveGeneratedFiles) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
try {
int var1 = var0.lastIndexOf(46);
Path var2;
if (var1 > 0) {
Path var3 = Paths.get(var0.substring(0, var1).replace('.', File.separatorChar));
Files.createDirectories(var3);
var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
} else {
var2 = Paths.get(var0 + ".class");
}
Files.write(var2, var4, new OpenOption[0]);
return null;
} catch (IOException var4x) {
throw new InternalError("I/O exception saving generated file: " + var4x);
}
}
});
}
return var4;
}
可以将属性saveGeneratedFiles
设置为true
时,查看最终生成的代理对象,
saveGeneratedFiles
属性初始化
private static final boolean saveGeneratedFiles = (Boolean)AccessController.doPrivileged(new GetBooleanAction("sun.misc.ProxyGenerator.saveGeneratedFiles"));
public static void main(String[] args) {
// 将saveGeneratedFiles置为true,运行
System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
Goods goods = new Goods();
Sales factory = new Factory();
ProxyHandler proxyHandler = new ProxyHandler(factory);
Object proxyInstance = Proxy.newProxyInstance(factory.getClass().getClassLoader(), new Class[]{Sales.class}, proxyHandler);
Sales proxy = (Sales) proxyInstance;
proxy.sale(goods);
}
最后能看到的生成的代理字节码如下:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.sun.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import org.example.proxy.core.Goods;
import org.example.proxy.core.Sales;
// 类继承了Proxy类,并实现了Sales接口
public final class $Proxy0 extends Proxy implements Sales {
private static Method m1;
private static Method m2;
private static Method m3;
private static Method m0;
// 构造函数 InvocationHandler 继承父类的实现
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}
// equals 方法实现
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);
}
}
//toString方法实现
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);
}
}
// 代理的方法实现 当前方法通过InvocationHandler对象执行了invoke方法
public final void sale(Goods var1) throws {
try {
super.h.invoke(this, m3, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}
// hashCode 实现
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);
}
}
// 加载类和方法到jvm中
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m2 = Class.forName("java.lang.Object").getMethod("toString");
m3 = Class.forName("org.example.proxy.core.Sales").getMethod("sale", Class.forName("org.example.proxy.core.Goods"));
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
}
至此,JDK动态代理源码跟踪完毕,不难总结出它的原理:
- 首先需要创建一个
InvocationHandler
实现类,并实现它的invoke
方法; - 通过
Proxy
类中的方法newProxyInstance
方法,创建返回代理对象,方法中需要将代理对象的ClassLoader
、实现的接口和第一步创建的InvocationHandler
传递进去。 - 在创建代理对象的过程中,会通过
Proxy
类中的方法getProxyClass0
先生成代理类,代理类是从缓存中获取,若缓存中没有通过Proxy
类中的内部类ProxyClassFactory
进行创建; ProxyClassFactory
中通过ProxyGenerator.generateProxyClass
方法创建字节码;- 最后通过
ProxyGenerator.defineClass0
方法生成代理类;
JDK动态代理应用
是Spring Aop
的底层技术,注解的底层实现、常用web拦截器等。