JDK 动态代理运行原理
Posted 叶长风
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDK 动态代理运行原理相关的知识,希望对你有一定的参考价值。
JDK 动态代理运行原理
- 程序演示
- 源码讲解
- 总结
这几天有空研究了下JDk的动态代理,JDK的动态代理类都在java.lang.reflect包下,写了一些小程序来演示了相关类的使用,同时做了一些与CGLIb的对比,以后有空再讲述下lombok中相关注解的使用。
1. 程序演示
接口:HelloWorld:
public interface HelloWorld
void sayHello();
对应的实现类为:
HelloWorldImpl:
public class HelloWorldImpl implements HelloWorld
@Override
public void sayHello()
System.out.println("Hello world");
接口与对应的实现的逻辑是比较简单的,在这只是讲述JDK动态代理的原理,业务逻辑也无需要复杂的业务逻辑。
代理类MyInvocationHandler:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* Created by xiaxuan on 17/11/7.
*/
public class MyInvocationHandler implements InvocationHandler
private Object target;
public MyInvocationHandler(Object target)
this.target = target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
System.out.println("before method invoke : " + method.getName());
return method.invoke(target, args);
测试类TestProxy:
import java.lang.reflect.Proxy;
/**
* Created by xiaxuan on 17/11/7.
*/
public class TestProxy
public static void main(String[] args)
HelloWorld hw = (HelloWorld) Proxy.newProxyInstance(HelloWorld.class.getClassLoader(), new Class[] HelloWorld.class, new MyInvocationHandler(new HelloWorldImpl()));
hw.sayHello();
运行结果为:
使用上其实还是挺简单的,以下是关键的动态代理的源码讲解。
2. 源码讲解
我们先进入Proxy.newProxyInstance()中查看,如下:
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
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);
......
我省略了后面的代码,上面的代码中关键的一行为
getProxyClass0(loader, intfs);
转到对应的方法为:
/**
* Generate a proxy class. Must call the checkProxyAccess method
* to perform permission checks before calling this.
*/
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
return proxyClassCache.get(loader, interfaces);
从proxyClassCache中取出class,进入到get方法中,如下:
public V get(K key, P parameter)
Objects.requireNonNull(parameter);
expungeStaleEntries();
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
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
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true)
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
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);
这里面关键的代码是以下两行:
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
这里真正生成代理类的源码为 subKeyFactory.apply(key, parameter)
但 Supplier<V> supplier = valuesMap.get(subKey)
,
这行代码中的Supplier对象并不是在运行到这的时候就能取到,而是在使用当前Supplier对象的时候才会实例化出来,这个是java8中的一个延迟加载的新特性。
进到方法subKeyFactory.apply(key, parameter)中,查看代码:
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.
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try
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());
其中这行代码
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
用来生成新的字节码替代运行。
我们可以用这行代码生成我们的代理类查看一下,新的方法如下:
public class TestProxy
public static void main(String[] args) throws IOException
HelloWorld hw = (HelloWorld) Proxy.newProxyInstance(HelloWorld.class.getClassLoader(), new Class[] HelloWorld.class, new MyInvocationHandler(new HelloWorldImpl()));
hw.sayHello();
createProxyClassFile();
//还原我们的代理类
public static void createProxyClassFile() throws IOException
byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy0", new Class[] HelloWorld.class );
FileOutputStream out = new FileOutputStream("$Proxy0.class");
out.write(bytes);
out.close();
```
使用intellij运行程序,生成的class保存在当前项目的根目录下,可以直接打开$Proxy.class文件,内容如下:
```
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
import cn.com.proxyDemo.HelloWorld;
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 HelloWorld
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)).booleanValue();
catch (RuntimeException | Error var3)
throw var3;
catch (Throwable var4)
throw new UndeclaredThrowableException(var4);
public final void sayHello() 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)).intValue();
catch (RuntimeException | Error var2)
throw var2;
catch (Throwable var3)
throw new UndeclaredThrowableException(var3);
static
try
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[]Class.forName("java.lang.Object"));
m3 = Class.forName("cn.com.proxyDemo.HelloWorld").getMethod("sayHello", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
catch (NoSuchMethodException var2)
throw new NoSuchMethodError(var2.getMessage());
catch (ClassNotFoundException var3)
throw new NoClassDefFoundError(var3.getMessage());
这个就是最终的代理类,继承Proxy并且实现了我们自己定义的HelloWorld。
在我们调用sayHello()方法的时候,实际上调用的是代理类中下下面一行代码:
public final void sayHello() throws
try
super.h.invoke(this, m3, (Object[])null);
catch (RuntimeException | Error var2)
throw var2;
catch (Throwable var3)
throw new UndeclaredThrowableException(var3);
而这行代码
super.h.invoke(this, m3, (Object[])null);
就是对应调用到我们写的
MyInvocationHandler中的
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
System.out.println("before method invoke : " + method.getName());
return method.invoke(target, args);
最终就起到一个动态代理的作用。
总结
动态代理,在第一次生成的对应的代理对象后,将其存在缓存中,然后再次调用的时候就直接从缓存中取出代理对象,然后调用对应的代理方法实现需要的效果。
在此就需要提下JDK这种动态代理和CGLIB这种的区别了, CGLIB一般是在编译阶段对生成的class进行替换,在实际运行的时候不需要再去生成字节码替换调用了,而JDK动态代理的话,在运行阶段生成代理类进行调用一般来说会稍微慢一些。
以后有空讲讲lombok中的@DATA注解的用法和原理,就是使用ASM在源码编译阶段生成class进行替换,相对于JDK动态代理来说速度要快许多。
以上是关于JDK 动态代理运行原理的主要内容,如果未能解决你的问题,请参考以下文章
Spring aop 基于JDK动态代理和CGLIB代理的原理以及为什么JDK代理需要基于接口