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動態代理來說速度要快許多。