JDK動態代理之原始碼分析
一、代理模式是什麼?
代理模式就是給一個物件提供一個代理物件,並由代理物件管理著被代理物件的引用。就像生活中的代理律師,你只需要找好代理律師,剩下的都交給代理律師來打理。
Spring MVC 有兩大特性,IoC 和 AOP。IoC為控制反轉,這裡不做介紹;AOP(Aspect Oriented Programming 面向切面程式設計)的實現就是基於代理技術。
二、靜態代理
先來看下什麼是靜態代理。靜態代理在程式執行前,就已經編寫好代理類,實現靜態代理需要以下:
1、定義業務介面
2、被代理物件實現業務介面
3、代理物件實現業務介面並持有被代理物件的引用
碼上看
2.1 業務介面
package cn.zjm.show.proxy;
/**
* @author Zhao JinMing
* @date 2018年9月14日 09:49
*/
public interface IUserService {
void add(String name);
}
2.2 被代理物件實現介面
package cn.zjm.show.proxy; /** * @author Zhao JinMing * @date 2018年9月14日 09:49 */ public class UserServiceImpl implements IUserService { @Override public void add(String name) { System.out.println("新增使用者“" + name + "”成功。"); } }
2.3 代理物件實現介面並持有代理物件引用
package cn.zjm.show.proxy; /** * @author Zhao JinMing * @date 2018年9月14日 09:50 */ public class UserServiceProxy implements IUserService { private IUserService proxy; public UserServiceProxy(IUserService proxy) { this.proxy = proxy; } @Override public void add(String name) { System.out.println("開始插入"); proxy.add(name); System.out.println("結束插入"); } }
2.4 程式碼測試
package cn.zjm.show.proxy;
public class SourceProxy {
public static void main(String[] args) {
IUserService userService = new UserServiceImpl();
IUserService proxy = new UserServiceProxy(userService);
proxy.add("王五");
}
}
2.5 輸出結果
開始插入
新增使用者“王五”成功。
結束插入
2.6 總結
既然已經有動態代理了,那為什麼還需要動態代理。毋庸置疑肯定是靜態代理與動態代理相比有著很多的缺陷。從擴充套件性的角度考慮,如果業務介面新增或者刪除方法,那麼不僅僅是被代理類需要修改,代理類也需要修改。而且對於不同的業務介面,需要寫不同的代理類,這麼麻煩的操作,怕麻煩的大佬肯定受不了,於是乎動態代理來了。
三、動態代理
所謂的動態代理,就是在程式執行的時候,根據需要動態的建立代理類及其例項來完成具體的操作。動態代理又分為JDK動態代理和cglib動態代理兩大類,下面介紹的是JDK動態代理。
3.1 使用JDK動態代理的步驟
①定義業務介面
②被代理物件實現業務介面
③通過Proxy的靜態方法newProxyInstance( ClassLoaderloader, Class[] interfaces, InvocationHandler h)建立一個代理物件
④使用代理物件
3.1 定義業務介面
package cn.zjm.show.proxy;
/**
* @author Zhao JinMing
* @date 2018年9月14日 09:49
*/
public interface IUserService {
void add(String name);
}
3.2 被代理物件實現業務介面
package cn.zjm.show.proxy;
/**
* @author Zhao JinMing
* @date 2018年9月14日 09:49
*/
public class UserServiceImpl implements IUserService {
@Override
public void add(String name) {
System.out.println("新增使用者“" + name + "”成功。");
}
}
3.3 建立代理物件並使用
package cn.zjm.show.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class SourceProxy {
public static void main(String[] args) {
IUserService userService = new UserServiceImpl();
IUserService proxy = (IUserService) Proxy.newProxyInstance(SourceProxy.class.getClassLoader(), userService.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("準備使用動態代理插入資料");
Object invoke = method.invoke(userService, args);
System.out.println("使用動態代理插入物件結束");
return invoke;
}
});
proxy.add("王五");
}
}
3.4 執行結果
準備使用動態代理插入資料
新增使用者“王五”成功。
使用動態代理插入物件結束
執行結果和靜態代理一樣,說明成功了。但是,我們注意到,我們並沒有像靜態代理那樣去自己定義一個代理類,並例項化代理物件。實際上,動態代理的代理物件是在記憶體中的,是JDK根據我們傳入的引數生成好的。那動態代理的代理類和代理物件是怎麼產生的呢?
四、原始碼分析
首先來看 newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
//判斷h是否為空
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.
* 用invocationHandler生成建構函式
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
//得到代理物件的建構函式
//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;
}
});
}
//生成代理物件
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(loader, intfs)得到代理類的Class物件,然後通過Class物件獲得構造方法,進而建立代理物件。再看getProxyClass0(loader, intfs)方法。
getProxyClass0(loader, intfs)
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
/*
如果由實現給定介面的給定載入器定義的代理類存在,則這將簡單地返回快取的副本;
否則,它將通過ProxyClassFactory建立代理類
*/
return proxyClassCache.get(loader, interfaces);
}
// private static final WeakCache<ClassLoader, Class<?>[], Class<?>> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
// proxyClassCache是WeakCache類的例項,WeakCache又是什麼?
再看看 WeakCache 是什麼
//K為key型別,P為引數型別,V為value型別
//根據傳進來的引數,K為ClassLoader型別,P為Class<?>[]型別,V為Class<?>型別
final class WeakCache<K, P, V> {
private final ReferenceQueue<K> refQueue
= new ReferenceQueue<>();
// the key type is Object for supporting null key
private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map
= new ConcurrentHashMap<>();
private final ConcurrentMap<Supplier<V>, Boolean> reverseMap
= new ConcurrentHashMap<>();
private final BiFunction<K, P, ?> subKeyFactory;
private final BiFunction<K, P, V> valueFactory;
public WeakCache(BiFunction<K, P, ?> subKeyFactory,
BiFunction<K, P, V> valueFactory) {
this.subKeyFactory = Objects.requireNonNull(subKeyFactory);
this.valueFactory = Objects.requireNonNull(valueFactory);
}
map變數為實現快取的核心變數,他是一個雙重map結構(key,sub-key。
在進入proxyClassCache.get(loader, interfaces)
public V get(K key, P parameter) {
//檢查引數是否為空
Objects.requireNonNull(parameter);
//清除無效的快取
expungeStaleEntries();
//cacheKey 為上述map中的一級key
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
//根據一級key得到ConcurrentMap<Object, Supplier<V>>物件,如果不存在,如果不存在就新建一個ConcurrentMap<Object, Supplier<V>>物件
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、獲取儲存的Supplier<V>
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
// 通過sub-key得到supplier
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true) {
//如果快取中有supplier,就直接通過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。
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.apply(key, parameter)
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)
CacheValue<V> cacheValue = new CacheValue<>(value);
// put into 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;
}
再看 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) {
/*
* 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());
}
}
}
獲取位元組碼檔案
package cn.zjm.show.proxy;
import sun.misc.ProxyGenerator;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class SourceProxy {
public static void main(String[] args) {
IUserService userService = new UserServiceImpl();
IUserService proxy = (IUserService) Proxy.newProxyInstance(SourceProxy.class.getClassLoader(), userService.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("動態代理開始");
Object invoke = method.invoke(userService, args);
System.out.println("動態代理結束");
return invoke;
}
});
proxy.add("王五");
String path = "D:/$Proxy0.class";
byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", userService.getClass().getInterfaces());
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
out.write(classFile);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
反編譯後
import cn.zjm.show.proxy.IUserService;
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 IUserService
{
private static Method m1;
private static Method m2;
private static Method m4;
private static Method m3;
private static Method m0;
public $Proxy0(InvocationHandler paramInvocationHandler)
throws
{
super(paramInvocationHandler);
}
public final boolean equals(Object paramObject)
throws
{
try
{
return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final String toString()
throws
{
try
{
return (String)this.h.invoke(this, m2, null);
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final void del(String paramString)
throws
{
try
{
this.h.invoke(this, m4, new Object[] { paramString });
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final void add(String paramString)
throws
{
try
{
this.h.invoke(this, m3, new Object[] { paramString });
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final int hashCode()
throws
{
try
{
return ((Integer)this.h.invoke(this, m0, null)).intValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m4 = Class.forName("cn.zjm.show.proxy.IUserService").getMethod("del", new Class[] { Class.forName("java.lang.String") });
m3 = Class.forName("cn.zjm.show.proxy.IUserService").getMethod("add", new Class[] { Class.forName("java.lang.String") });
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
}