jdk动态代理原理分析
一、为什么要用代理
玩过扮白脸、扮黑脸的游戏吗?你是个白脸,提供很友善的服务,但是你不希望每个人都叫你做事,所以找了黑脸控制对你的访问。这就是代理要做的:控制和管理访问。就像你将看到的,代理的方式有许多种。代理以通过Internet为它们的代理对象搬运的整个方法调用而出名,它也可以代替某些懒惰的对象做一些事情。 — 引用自Head First 设计模式
- 代理就是
控制目标对象的访问
;那么为什么需要代理呢? - 假设第一个场景:
- 系统用户有2种,分别是游客用户和正式用户;必然的游客用户有些功能是不能用的,对应的就是后台某些方法是不能给他调用的;如果是在方法内部加判断的话就比较费力,当然这是一个解决方案;不过这种实现并不优雅。用过spring aop的都知道可以用环绕来解决这个问题,spring aop原理就是使用代理。
- 第二个场景:
- 比如一个
RPC
框架,我本地语义调用一个service
接口的方法,最终会调用到远程的方法。其内部原理就是给service
接口生成一个代理,代理内部就是调用远程地址。客户端拿到的service接口对象是一个代理对象。
- 比如一个
- 代理功能很强大比如aop、事务这些都可以通过代理去实现。
二、使用jdk代理
- 要实现jdk的动态代理比较简单(
jdk动态代理目标对象必须有实现接口
)- 1、创建好
service
和service的实现
- 2、实现
InvocationHandler
接口写一个实现类 - 3、调用创建代理的方法
Proxy.newProxyInstance
- 1、创建好
- 下面就按照步骤来:
- 1、创建
UserService.java
和UserServiceImpl.java
package com.zzq.test.proxy;
public interface UserService {
public void test() throws Throwable ;
}
package com.zzq.test.proxy;
public class UserServiceImpl implements UserService{
@Override
public void test() throws Throwable {
System.out.println("进入test方法");
}
}
- 2、
JdkProxyInvocationHandler.java
package com.zzq.test.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class JdkProxyInvocationHandler implements InvocationHandler {
private UserService userService;
public JdkProxyInvocationHandler(UserService userService){
this.userService = userService;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
method.invoke(userService, args);
return null;
}
}
- 3、
JdkProxyTest.java
为了能说的更明了,我把jdk动态代理要生成的class保存了
package com.zzq.test.proxy;
import sun.misc.ProxyGenerator;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;
@SuppressWarnings("restriction")
public class JdkProxyTest {
private static String DEFAULT_CLASS_NAME = "$Proxy0";
public static void main(String[] args) {
// 保存生成的代理类的字节码文件
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
UserService userService = new UserServiceImpl();
//第一个参数是指定代理类的类加载器(我们传入当前测试类的类加载器)
//第二个参数是代理类需要实现的接口(我们传入被代理类实现的接口,这样生成的代理类和被代理类就实现了相同的接口)
//第三个参数是invocation handler,用来处理方法的调用。这里传入我们自己实现的handler
UserService service = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(),
new Class[] { UserService.class }, new JdkProxyInvocationHandler(userService));
try {
service.test();
} catch (Throwable e) {
e.printStackTrace();
}
//createProxyClassFile(UserService.class);
}
private static void createProxyClassFile(Class<?> c) {
byte[] data = ProxyGenerator.generateProxyClass(DEFAULT_CLASS_NAME, new Class[] { c });
FileOutputStream out = null;
try {
String filePath = JdkProxyTest.class.getResource("/").getPath().substring(1) + DEFAULT_CLASS_NAME
+ ".class";
out = new FileOutputStream(filePath);
out.write(data);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
// ignore
}
}
}
}
- 下面就是运行一波看结果
- class也生成了
三、jdk动态代理实现原理分析
(第一次写这种时序图,见笑了)
- 到源码
Proxy#newProxyInstance
方法
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
//检验h不为空,h为空抛异常 也就是我们传进来的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对象。
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
//得到代理类对象的构造函数,这个构造函数的参数由constructorParams指定
//参数constructorParames为常量值:private static final Class<?>[] constructorParams = { InvocationHandler.class };
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;
}
});
}
//这里生成代理对象,传入的参数new Object[]{h}后面讲 h便是InvocationHandler的实现类
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) {
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
//意思是:如果代理类被指定的类加载器loader定义了,并实现了给定的接口interfaces,
//那么就返回缓存的代理类对象,否则使用ProxyClassFactory创建代理类。
return proxyClassCache.get(loader, interfaces);
}
proxyClassCache是个WeakCache类的对象,调用proxyClassCache.get(loader, interfaces); 可以得到缓存的代理类或创建代理类(没有缓存的情况)
WeakCache#get
//K和P就是WeakCache定义中的泛型,key是类加载器,parameter是接口类数组
public V get(K key, P parameter) {
//检查parameter不为空
Objects.requireNonNull(parameter);
//清除无效的缓存
expungeStaleEntries();
// cacheKey就是(key, sub-key) -> value里的一级key,
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
// map实现缓存的核心变量
//根据一级key得到 ConcurrentMap<Object, Supplier<V>>对象。如果之前不存在,则新建一个ConcurrentMap<Object, Supplier<V>>和cacheKey(一级key)一起放到map中。
ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
if (valuesMap == null) {
ConcurrentMap<Object, Supplier<V>> oldValuesMap
= map.putIfAbsent(cacheKey,
valuesMap = new ConcurrentHashMap<>());
if (oldValuesMap != null) {
valuesMap = oldValuesMap;
}
}
// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
//这部分就是调用生成sub-key的代码,上面我们已经看过怎么生成的了
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
//通过sub-key得到supplier 如果是相同的subKey则返回之前的
Supplier<V> supplier = valuesMap.get(subKey);
//supplier实际上就是这个factory
Factory factory = null;
while (true) {
//如果缓存里有supplier ,那就直接通过get方法,得到代理类对象,返回,就结束了,一会儿分析get方法。
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
V value = supplier.get();
if (value != null) {
return value;
}
}
// else no supplier in cache
// or a supplier that returned null (could be a cleared CacheValue
// or a Factory that wasn't successful in installing the CacheValue)
// lazily construct a Factory
//下面的所有代码目的就是:如果缓存中没有supplier,则创建一个Factory对象,把factory对象在多线程的环境下安全的赋给supplier。
//因为是在while(true)中,赋值成功后又回到上面去调get方法,返回才结束。
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}
if (supplier == null) {
// 加入缓存
supplier = valuesMap.putIfAbsent(subKey, factory);
if (supplier == null) {
// successfully installed Factory
supplier = factory;
}
// else retry with winning supplier
} else {
if (valuesMap.replace(subKey, supplier, factory)) {
// successfully replaced
// cleared CacheEntry / unsuccessful Factory
// with our Factory
supplier = factory;
} else {
// retry with current supplier
supplier = valuesMap.get(subKey);
}
}
}
}
Factory#get
public synchronized V get() { // serialize access
// re-check
Supplier<V> supplier = valuesMap.get(subKey);
//重新检查得到的supplier是不是当前对象
if (supplier != this) {
// something changed while we were waiting:
// might be that we were replaced by a CacheValue
// or were removed because of failure ->
// return null to signal WeakCache.get() to retry
// the loop
return null;
}
// else still us (supplier == this)
// create new value
V value = null;
try {
//代理类就是在这个位置调用valueFactory生成的
//valueFactory就是我们传入的 new ProxyClassFactory()
//一会我们分析ProxyClassFactory()的apply方法
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
// the only path to reach here is with non-null value
assert value != null;
// wrap value with CacheValue (WeakReference)
//把value包装成弱引用
CacheValue<V> cacheValue = new CacheValue<>(value);
// put into reverseMap
// reverseMap是用来实现缓存的有效性
reverseMap.put(cacheValue, Boolean.TRUE);
// try replacing us with CacheValue (this should always succeed)
if (!valuesMap.replace(subKey, this, cacheValue)) {
throw new AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
- 这里我插入一下缓存的逻辑我debug简单演示下:
- subKey是这样子的
- 如果我是重复创建的话就会取缓存
- subKey是这样子的
- 来到
ProxyClassFactory#apply
方法,代理类就是在这里生成的
//这里的BiFunction<T, U, R>是个函数式接口,可以理解为用T,U两种类型做参数,得到R类型的返回值
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
//代理类访问控制符: public ,final
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.
*/
//验证所有非公共的接口在同一个包内;公共的就无需处理
//生成包名和类名的逻辑,包名默认是com.sun.proxy,类名默认是$Proxy 加上一个自增的整数值
//如果被代理类是 non-public proxy interface ,则用和被代理类接口一样的包名
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.
*/
long num = nextUniqueNumber.getAndIncrement();
//代理类的完全限定名,如com.sun.proxy.$Proxy0.calss
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
*/
//核心部分,生成代理类的字节码
// 核心代码下面有
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
//把代理类加载到JVM中,至此动态代理过程基本结束了
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
throw new IllegalArgumentException(e.toString());
}
}
}
- 生成代理类字节码
ProxyGenerator#generateProxyClass
public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
// 生成代理类的字节码
final byte[] var4 = var3.generateClassFile();
// 是否要将生成代理类的字节码文件保存到磁盘中,该变量可以通过系统属性设置 主要就是配置这个属性 sun.misc.ProxyGenerator.saveGeneratedFiles
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;
}
- 最后分析下生成的class文件就明白了。
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
import com.zzq.test.proxy.UserService;
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 UserService {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public $Proxy0(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 test() throws Throwable {
super.h.invoke(this, m3, (Object[])null);
}
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.zzq.test.proxy.UserService").getMethod("test");
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());
}
}
}
- 代码
UserService service = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(),
new Class[] { UserService.class }, new JdkProxyInvocationHandler(userService))
service
返回的对象就是上面生成的那个类实例化的对象,当我调用test
方法时super.h.invoke(this, m3, (Object[])null);
,调用的是InvocationHandler
实现类JdkProxyInvocationHandler
的invoke
方法。
四、小总结
- 总结下重要的实现步骤(其中如果是有缓存的话2、3步骤是取缓存):
- 1、基本校验
- 2、生成代理类
- 3、加载到jvm
- 4、构造方法实例化代理对象
- 本人水平有限,如果文章有误的地方,希望批评指正,感谢您的观看。