前言: 最近學習Hadoop系列的知識,免不了和RPC打交道,而RPC又使用動態代理來實現。沿著這條脈絡,秉著鉆研的精神,準備深入學習一下動態代理。本文準備按照以下順序一步一步講解動態代理,讓大家知其所以更知其所以然。
一、為什么需要動態代理
1.1 從代理模式說起
?????代理模式是指給某一個對象提供一個代理對象,并由代理對象控制對原對象的引用。通俗的來講代理模式就是我們生活中常見的中介。這種模式有什么用呢?它可以在原對象的基礎上增強原對象的功能,比如在原對象調用一個方法的前后進行日志、事務操作等。Spring AOP就使用了代理模式。
1.2 代理模式----靜態代理
?????如何實現代理模式呢?首先來看靜態代理。靜態代理是指在程序運行前就已經存在的編譯好的代理類是為靜態代理。實現靜態代理有四個步驟:
?????①定義業務接口;
?????②被代理類實現業務接口;
?????③定義代理類并實現業務接口;
?????④最后便可通過客戶端進行調用。(這里可以理解成程序的main方法里的內容)
?????我們按照這個步驟去實現靜態代理。需求:在向數據庫添加一個用戶時前后打印日志。
1.2.1業務接口
IUserService.java
package com.zhb.jdk.proxy;
/**
*@author ZHB
*@date 2018年8月31日下午10:44:49
*@todo TODO
*/
public interface IUserService {
void add(String name);
}
1.2.2被代理類實現業務接口
UserServiceImpl.java
package com.zhb.jdk.proxy;
/**
*@author ZHB
*@date 2018年8月31日下午10:47:25
*@todo TODO
*/
public class UserServiceImpl implements IUserService{
@Override
public void add(String name) {
System.out.println("向數據庫中插入名為: "+name+" 的用戶");
}
}
1.2.3定義代理類并實現業務接口
?????因為代理對象和被代理對象需要實現相同的接口。所以代理類源文件UserServiceProxy.java這么寫:
package com.zhb.jdk.proxy;
/**
* @author ZHB
* @date 2018年8月31日下午10:51:39
* @todo TODO
*/
public class UserServiceProxy implements IUserService {
// 被代理對象
private IUserService target;
// 通過構造方法傳入被代理對象
public UserServiceProxy(IUserService target) {
this.target = target;
}
@Override
public void add(String name) {
System.out.println("準備向數據庫中插入數據");
target.add(name);
System.out.println("插入數據庫成功");
}
}
?????由于代理類(UserServiceProxy )和被代理類(UserServiceImpl )都實現了IUserService接口,所以都有add方法,在代理類的add方法中調用了被代理類的add方法,并在其前后各打印一條日志。
1.2.4客戶端調用
package com.zhb.jdk.proxy;
/**
*@author ZHB
*@date 2018年8月31日下午11:01:12
*@todo TODO
*/
public class StaticProxyTest {
public static void main(String[] args) {
IUserService target = new UserServiceImpl();
UserServiceProxy proxy = new UserServiceProxy(target);
proxy.add("陳粒");
}
}
執行結果如下:
靜態代理我們就實現了。
1.3 代理模式----動態代理
?????既然有了靜態代理,為什么會出現動態代理呢?那我們就說一下靜態代理的一些缺點吧:
?????①代理類和被代理類實現了相同的接口,導致代碼的重復,如果接口增加一個方法,那么除了被代理類需要實現這個方法外,代理類也要實現這個方法,增加了代碼維護的難度。
?????②代理對象只服務于一種類型的對象,如果要服務多類型的對象。勢必要為每一種對象都進行代理,靜態代理在程序規模稍大時就無法勝任了。比如上面的例子,只是對用戶的業務功能(IUserService)進行代理,如果是商品(IItemService)的業務功能那就無法代理,需要去編寫商品服務的代理類。
?????于是乎,動態代理的出現就能幫助我們解決靜態代理的不足。所謂動態代理是指:在程序運行期間根據需要動態創建代理類及其實例來完成具體的功能。動態代理主要分為JDK動態代理和cglib動態代理兩大類,本文主要對JDK動態代理進行探討。
二、動態代理實例
2.1 使用JDK動態代理步驟
?????①創建被代理的接口和類;
?????②創建InvocationHandler接口的實現類,在invoke方法中實現代理邏輯;
?????③通過Proxy的靜態方法newProxyInstance( ClassLoaderloader, Class[] interfaces, InvocationHandler h)
創建一個代理對象
?????④使用代理對象。
2.2 Demo
?????還是我們剛才的需求,這次換用動態代理實現:
2.2.1 創建被代理的接口和類
?????這個和靜態代理的源碼相同,還是使用上面的IUserService.java
和UserServiceImpl.java
2.2.2 創建InvocationHandler接口的實現類
package com.zhb.jdk.dynamicProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* @author ZHB
* @date 2018年8月31日下午11:25:53
* @todo TODO
*/
public class MyInvocationHandler implements InvocationHandler {
//被代理對象,Object類型
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("準備向數據庫中插入數據");
Object returnvalue = method.invoke(target, args);
System.out.println("插入數據庫成功");
return returnvalue;
}
}
2.2.3 通過Proxy的靜態方法創建代理對象并使用代理對象
?????代碼中有注釋:
package com.zhb.jdk.dynamicProxy;
import java.lang.reflect.Proxy;
/**
* @author ZHB
* @date 2018年8月31日下午11:35:07
* @todo TODO
*/
public class DynamicProxyTest {
public static void main(String[] args) {
IUserService target = new UserServiceImpl();
MyInvocationHandler handler = new MyInvocationHandler(target);
//第一個參數是指定代理類的類加載器(我們傳入當前測試類的類加載器)
//第二個參數是代理類需要實現的接口(我們傳入被代理類實現的接口,這樣生成的代理類和被代理類就實現了相同的接口)
//第三個參數是invocation handler,用來處理方法的調用。這里傳入我們自己實現的handler
IUserService proxyObject = (IUserService) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(),
target.getClass().getInterfaces(), handler);
proxyObject.add("陳粒");
}
}
?????運行結果和靜態代理一樣,說明成功了。但是,我們注意到,我們并沒有像靜態代理那樣去自己定義一個代理類,并實例化代理對象。實際上,動態代理的代理對象是在內存中的,是JDK根據我們傳入的參數生成好的。那動態代理的代理類和代理對象是怎么產生的呢?重頭戲來了,且往下看。
三、動態代理源碼深入分析
?????這部分如果想要更快更好的理解,建議一邊對著源碼(本文JDK 1.8),一邊看著博客。畢竟自己親身實踐效果才好嘛。
?????Proxy.newProxyInstance( ClassLoaderloader, Class[] interfaces, InvocationHandler h)
產生了代理對象,所以我們進到newProxyInstance
的實現:
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
//檢驗h不為空,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.
*/
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}后面講
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
這個方法。
//此方法也是Proxy類下的方法
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,有Cache便知道是緩存的意思,正好呼應了前面Look up or generate the designated proxy class。查詢(在緩存中已經有)或生成指定的代理類的class對象這段注釋。
?????在進入get方法之前,我們看下 proxyClassCache
是什么?高能預警,前方代碼看起來可能有亂,但我們只需要關注重點即可。
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
?????proxyClassCache
是個WeakCache類的對象,調用proxyClassCache.get(loader, interfaces); 可以得到緩存的代理類或創建代理類(沒有緩存的情況)。說明WeakCache中有get
這個方法。先看下WeakCache類的定義(這里先只給出變量的定義和構造函數):
//K代表key的類型,P代表參數的類型,V代表value的類型。
// WeakCache<ClassLoader, Class<?>[], Class<?>> proxyClassCache 說明proxyClassCache存的值是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) -> value
。其中key是傳進來的Classloader進行包裝后的對象,sub-key是由WeakCache構造函數傳人的KeyFactory()
生成的。value就是產生代理類的對象,是由WeakCache構造函數傳人的ProxyClassFactory()
生成的。如下,回顧一下:
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
?????產生sub-key的KeyFactory代碼如下,這個我們不去深究,只要知道他是根據傳入的ClassLoader和接口類生成sub-key即可。
private static final class KeyFactory
implements BiFunction<ClassLoader, Class<?>[], Object>
{
@Override
public Object apply(ClassLoader classLoader, Class<?>[] interfaces) {
switch (interfaces.length) {
case 1: return new Key1(interfaces[0]); // the most frequent
case 2: return new Key2(interfaces[0], interfaces[1]);
case 0: return key0;
default: return new KeyX(interfaces);
}
}
}
?????通過sub-key拿到一個Supplier<Class<?>>
對象,然后調用這個對象的get方法,最終得到代理類的Class對象。
好,大體上說完WeakCache這個類的作用,我們回到剛才proxyClassCache.get(loader, interfaces);
這句代碼。get是WeakCache里的方法。源碼如下:
//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
//根據一級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
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;
}
}
?????撥云見日,來到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());
}
}
}
?????到這里其實已經分析完了,但是本著深究的態度,決定看看JDK生成的動態代理字節碼是什么,于是我們將字節碼保存到磁盤上的class文件中。代碼如下:
package com.zhb.jdk.proxy;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;
import com.zhb.jdk.dynamicProxy.HelloworldImpl;
import sun.misc.ProxyGenerator;
/**
* @author ZHB
* @date 2018年8月31日下午11:35:07
* @todo TODO
*/
public class DynamicProxyTest {
public static void main(String[] args) {
IUserService target = new UserServiceImpl();
MyInvocationHandler handler = new MyInvocationHandler(target);
//第一個參數是指定代理類的類加載器(我們傳入當前測試類的類加載器)
//第二個參數是代理類需要實現的接口(我們傳入被代理類實現的接口,這樣生成的代理類和被代理類就實現了相同的接口)
//第三個參數是invocation handler,用來處理方法的調用。這里傳入我們自己實現的handler
IUserService proxyObject = (IUserService) Proxy.newProxyInstance(DynamicProxyTest.class.getClassLoader(),
target.getClass().getInterfaces(), handler);
proxyObject.add("陳粒");
String path = "D:/$Proxy0.class";
byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0", HelloworldImpl.class.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();
}
}
}
}
?????運行這段代碼,會在D盤生成一個名為$Proxy0.class的文件。通過反編譯工具,得到JDK為我們生成的代理類是這樣的:
// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space
import com.zhb.jdk.proxy.IUserService;
import java.lang.reflect.*;
public final class $Proxy0 extends Proxy
implements IUserService
{
private static Method m1;
private static Method m2;
private static Method m3;
private static Method m0;
//代理類的構造函數,其參數正是是InvocationHandler實例,
//Proxy.newInstance方法就是通過通過這個構造函數來創建代理實例的
public $Proxy0(InvocationHandler invocationhandler)
{
super(invocationhandler);
}
// Object類中的三個方法,equals,toString, hashCode
public final boolean equals(Object obj)
{
try
{
return ((Boolean)super.h.invoke(this, m1, new Object[] {
obj
})).booleanValue();
}
catch (Error ) { }
catch (Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
public final String toString()
{
try
{
return (String)super.h.invoke(this, m2, null);
}
catch (Error ) { }
catch (Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
//接口代理方法
public final void add(String s)
{
try
{
// invocation handler的 invoke方法在這里被調用
super.h.invoke(this, m3, new Object[] {
s
});
return;
}
catch (Error ) { }
catch (Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
public final int hashCode()
{
try
{
// 在這里調用了invoke方法。
return ((Integer)super.h.invoke(this, m0, null)).intValue();
}
catch (Error ) { }
catch (Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
// 靜態代碼塊對變量進行一些初始化工作
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]);
m3 = Class.forName("com.zhb.jdk.proxy.IUserService").getMethod("add", new Class[] {
Class.forName("java.lang.String")
});
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
}
catch (NoSuchMethodException nosuchmethodexception)
{
throw new NoSuchMethodError(nosuchmethodexception.getMessage());
}
catch (ClassNotFoundException classnotfoundexception)
{
throw new NoClassDefFoundError(classnotfoundexception.getMessage());
}
}
}
?????生成了Object類的三個方法:toString,hashCode,equals。還有我們需要被代理的方法。
?????至此整個JDK動態代理的過程,就分析完了,感覺神清氣爽啊。