一、理解
- 靜態(tài)代理:靜態(tài)代理是在編譯時(shí)就將接口、實(shí)現(xiàn)類、代理類一股腦兒全部手動(dòng)完成
- 動(dòng)態(tài)代理:在程序運(yùn)行期間根據(jù)需要?jiǎng)討B(tài)的創(chuàng)建代理類及其實(shí)例坟漱,來完成具體的功能
二、應(yīng)用場景
- 參考裝飾器模式更哄,在已有的方法中進(jìn)行再次封裝芋齿,實(shí)現(xiàn)新增功能
- AOP面向切面編程思想
三、實(shí)現(xiàn)代碼
在了解了動(dòng)態(tài)代理之前成翩,我們先通過最簡單的例子看靜態(tài)代理是如何實(shí)現(xiàn)的觅捆。
先定義一個(gè)接口
package about_proxy.static_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public interface Subject {
public void doSomething();
}
完成一個(gè)該接口的實(shí)現(xiàn)類,并實(shí)現(xiàn)doSomething方法
package about_proxy.static_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class RealSubject implements Subject {
@Override
public void doSomething() {
System.out.println("call doSomething()");
}
}
假如這時(shí)有需求麻敌,需要改寫doSomething方法栅炒,再方法執(zhí)行前后增加日志打印功能,并計(jì)算該功能耗時(shí),可是其中實(shí)現(xiàn)邏輯復(fù)雜<貌似并不復(fù)雜赢赊,只有一句打印乙漓,不要在意這些細(xì)節(jié)。>释移,不想修改原有代碼叭披,這時(shí)我們新建一個(gè)代理類,在其中實(shí)現(xiàn)我們需要的功能玩讳。
package about_proxy.static_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class SubjectProxy implements Subject {
Subject subimpl = new RealSubject();
@Override
public void doSomething() {
System.out.println("我們先做點(diǎn)什么");
subimpl.doSomething();
System.out.println("我們?cè)僮鳇c(diǎn)什么");
}
}
這個(gè)時(shí)候我們就可以利用新的代理類來實(shí)現(xiàn)新的需求涩蜘,而不用修改源代碼。下面完成測試類
package about_proxy.static_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class TestStaticProxy {
public static void main(String args[]) {
// Subject sub = new RealSubject();
Subject sub = new SubjectProxy();
sub.doSomething();
}
}
好啦熏纯,這時(shí)候我們已經(jīng)完成了需求人員的要求了同诫。可是這個(gè)時(shí)候豆巨,老板又跳出來剩辟,說我想測試一下工程中多個(gè)類中方法的耗時(shí)掐场。
干往扔!我要新建多少個(gè)代理類啊。
這個(gè)時(shí)候動(dòng)態(tài)代理就應(yīng)運(yùn)而生了熊户。首先我們還是定義接口
package about_proxy.dynamic_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public interface Subject {
public void doSomething();
}
然后定義實(shí)現(xiàn)類
package about_proxy.dynamic_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class RealSubject implements Subject {
@Override
public void doSomething() {
System.out.println("call doSomething()");
}
}
上面我們就完成了準(zhǔn)備工作萍膛,接下來實(shí)現(xiàn)動(dòng)態(tài)代理
package about_proxy.dynamic_proxy;
import org.omg.CORBA.portable.InvokeHandler;
import sun.rmi.runtime.Log;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class ProxyHandler implements InvocationHandler {
private Object tar;
public Object bind(Object tar)
{
this.tar = tar;
//綁定該類實(shí)現(xiàn)的所有接口,取得代理類
return Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
//這里就可以進(jìn)行所謂的AOP編程了
//在調(diào)用具體函數(shù)方法前嚷堡,執(zhí)行功能處理
System.out.println("start time:"+System.currentTimeMillis());
result = method.invoke(tar,args);
//在調(diào)用具體函數(shù)方法后蝗罗,執(zhí)行功能處理
System.out.println("end time:"+System.currentTimeMillis());
return result;
}
}
最后再測試類中使用動(dòng)態(tài)代理
package about_proxy.dynamic_proxy;
/**
* Created by solie_h on 2018/2/7.
*/
public class TestDynamicProxy {
public static void main(String args[]){
// Subject sub = new RealSubject();
ProxyHandler proxy = new ProxyHandler();
//綁定該類實(shí)現(xiàn)的所有接口
Subject sub = (Subject) proxy.bind(new RealSubject());
sub.doSomething();
}
}
這樣我們就可以在一個(gè)ProxyHandler實(shí)現(xiàn)多個(gè)代理類的功能(本demo只使用了一個(gè)動(dòng)態(tài)代理),但是只創(chuàng)建了一個(gè)實(shí)體類蝌戒。是如何實(shí)現(xiàn)的呢串塑?動(dòng)態(tài)代理其實(shí)為我們?cè)谶\(yùn)行期間動(dòng)態(tài)生成了多個(gè)代理類,下面我們通過源碼來了解一下jdk中是如何操作的北苟。
四桩匪、原理簡析
我們可以debug一下demo,當(dāng)工程執(zhí)行到doSomething()方法時(shí)進(jìn)入了ProxyHandler類中的invoke方法友鼻,以實(shí)現(xiàn)了我們?cè)谡嬲膁oSomething()方法前后增加了自己想要的功能傻昙。
為什么會(huì)進(jìn)入invoke中呢?
在上述demo的main方法中調(diào)用了ProxyHandler的bind方法彩扔,
Subject sub = (Subject) proxy.bind(new RealSubject());
其實(shí)是調(diào)用了Proxy類的靜態(tài)方法newProxyInstance()
Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this);
這里便是生成代理的關(guān)鍵了妆档,我們繼續(xù)跟進(jìn)查看內(nèi)部關(guān)鍵
@CallerSensitive
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);
}
/*
* 獲取代理類。
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* 使用指定的invocationHandler調(diào)用構(gòu)造方法
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
//調(diào)用代理對(duì)象的構(gòu)造函數(shù)(代理對(duì)象的構(gòu)造函數(shù)$Proxy0(InvocationHandler h)虫碉,通過字節(jié)碼反編譯可以查看生成的代理類)
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;
}
});
}
//生成代理類的實(shí)例贾惦,并把MyInvocationHander的實(shí)例作為構(gòu)造函數(shù)參數(shù)傳入
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);
}
}
我們繼續(xù)看是如何獲取代理類的,跟入Class<?> cl = 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) {
//實(shí)現(xiàn)接口的最大數(shù)量<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
//調(diào)用了get方法
return proxyClassCache.get(loader, interfaces);
}
繼續(xù)跟入proxyClassCache.get(loader, interfaces);
/**
* @param key 上面?zhèn)魅氲膌oader,類加載器
* @param parameter 上面方法傳入的interfaces纤虽,接口數(shù)組
*/
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
// 返回的value是通過該方法調(diào)用的
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);
}
}
}
}
我們繼續(xù)查看supplier.get()方法乳绕,該方法的實(shí)現(xiàn)在WeakCache的內(nèi)部類Factory中,代碼如下
@Override
public synchronized V get() { // serialize access
// re-check
Supplier<V> supplier = valuesMap.get(subKey);
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進(jìn)行返回
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);
// try replacing us with CacheValue (this should always succeed)
if (valuesMap.replace(subKey, this, cacheValue)) {
// put also in reverseMap
reverseMap.put(cacheValue, Boolean.TRUE);
} else {
throw new AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
繼續(xù)跟蹤valueFactory.apply(key, parameter)方法逼纸,該方法的實(shí)現(xiàn)在Proxy的內(nèi)部類ProxyClassFactory中
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
/*
* 確保該loader加載的此類(intf)
*/
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");
}
/*
* 確保是一個(gè)接口
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* 確保接口沒重復(fù)
*/
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;
/*
* 驗(yàn)證所有非公共的接口在同一個(gè)包內(nèi)洋措;公共的就無需處理.
*/
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 + ".";
}
/*
* 為代理類生成一個(gè)名字,防止重復(fù)
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* 具體生成代理類的方法又在該方法中實(shí)現(xiàn)
*/
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());
}
}
}
再跟蹤ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags)
public static byte[] generateProxyClass(final String name, Class<?>[] interfaces, int accessFlags) {
ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
//真正生成字節(jié)碼的方法
final byte[] classFile = gen.generateClassFile();
//如果saveGeneratedFiles為true 則生成字節(jié)碼文件杰刽,所以在開始我們要設(shè)置這個(gè)參數(shù)
//當(dāng)然菠发,也可以通過返回的bytes自己輸出
if (saveGeneratedFiles) {
java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() {
public Void run() {
try {
int i = name.lastIndexOf('.');
Path path;
if (i > 0) {
Path dir = Paths.get(name.substring(0, i).replace('.', File.separatorChar));
Files.createDirectories(dir);
path = dir.resolve(name.substring(i+1, name.length()) + ".class");
} else {
path = Paths.get(name + ".class");
}
Files.write(path, classFile);
return null;
} catch (IOException e) {
throw new InternalError( "I/O exception saving generated file: " + e);
}
}
});
}
return classFile;
}
繼續(xù)跟生成自己碼的代碼,這里便是最終的生成方法了
private byte[] generateClassFile() {
/* ============================================================
* Step 1: Assemble ProxyMethod objects for all methods to generate proxy dispatching code for.
* 步驟1:為所有方法生成代理調(diào)度代碼贺嫂,將代理方法對(duì)象集合起來滓鸠。
*/
//增加 hashcode、equals第喳、toString方法
addProxyMethod(hashCodeMethod, Object.class);
addProxyMethod(equalsMethod, Object.class);
addProxyMethod(toStringMethod, Object.class);
//增加接口方法
for (Class<?> intf : interfaces) {
for (Method m : intf.getMethods()) {
addProxyMethod(m, intf);
}
}
/*
* 驗(yàn)證方法簽名相同的一組方法糜俗,返回值類型是否相同;意思就是重寫方法要方法簽名和返回值一樣
*/
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
checkReturnTypes(sigmethods);
}
/* ============================================================
* Step 2: Assemble FieldInfo and MethodInfo structs for all of fields and methods in the class we are generating.
* 為類中的方法生成字段信息和方法信息
*/
try {
//增加構(gòu)造方法
methods.add(generateConstructor());
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
// add static field for method's Method object
fields.add(new FieldInfo(pm.methodFieldName,
"Ljava/lang/reflect/Method;",
ACC_PRIVATE | ACC_STATIC));
// generate code for proxy method and add it
methods.add(pm.generateMethod());
}
}
//增加靜態(tài)初始化信息
methods.add(generateStaticInitializer());
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception", e);
}
if (methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
}
if (fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
}
/* ============================================================
* Step 3: Write the final class file.
* 步驟3:編寫最終類文件
*/
/*
* Make sure that constant pool indexes are reserved for the following items before starting to write the final class file.
* 在開始編寫最終類文件之前曲饱,確保為下面的項(xiàng)目保留常量池索引悠抹。
*/
cp.getClass(dotToSlash(className));
cp.getClass(superclassName);
for (Class<?> intf: interfaces) {
cp.getClass(dotToSlash(intf.getName()));
}
/*
* Disallow new constant pool additions beyond this point, since we are about to write the final constant pool table.
* 設(shè)置只讀,在這之前不允許在常量池中增加信息扩淀,因?yàn)橐獙懗A砍乇? */
cp.setReadOnly();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
// u4 magic;
dout.writeInt(0xCAFEBABE);
// u2 次要版本;
dout.writeShort(CLASSFILE_MINOR_VERSION);
// u2 主版本
dout.writeShort(CLASSFILE_MAJOR_VERSION);
cp.write(dout); // (write constant pool)
// u2 訪問標(biāo)識(shí);
dout.writeShort(accessFlags);
// u2 本類名;
dout.writeShort(cp.getClass(dotToSlash(className)));
// u2 父類名;
dout.writeShort(cp.getClass(superclassName));
// u2 接口;
dout.writeShort(interfaces.length);
// u2 interfaces[interfaces_count];
for (Class<?> intf : interfaces) {
dout.writeShort(cp.getClass(
dotToSlash(intf.getName())));
}
// u2 字段;
dout.writeShort(fields.size());
// field_info fields[fields_count];
for (FieldInfo f : fields) {
f.write(dout);
}
// u2 方法;
dout.writeShort(methods.size());
// method_info methods[methods_count];
for (MethodInfo m : methods) {
m.write(dout);
}
// u2 類文件屬性:對(duì)于代理類來說沒有類文件屬性;
dout.writeShort(0); // (no ClassFile attributes for proxy classes)
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception", e);
}
return bout.toByteArray();
}
上面對(duì)源碼一頓分析楔敌,接下來我們將demo中調(diào)用bind方法中Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this)動(dòng)態(tài)生成的代理類打印出來,修改我們的demo
package about_proxy.dynamic_proxy;
import sun.misc.ProxyGenerator;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by solie_h on 2018/2/7.
*/
public class TestDynamicProxy {
public static void main(String args[]){
// Subject sub = new RealSubject();
ProxyHandler proxy = new ProxyHandler();
//綁定該類實(shí)現(xiàn)的所有接口
Subject sub = (Subject) proxy.bind(new RealSubject());
// 將動(dòng)態(tài)生成的代理類打印出來
// 這里需要修改為你需要輸出的路徑
String path = "請(qǐng)修改路徑/TestProxy.class";
byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0",RealSubject.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();
}
}
sub.doSomething();
}
}
將生成的TestProxy.class文件反編譯驻谆,這里給不熟悉反編譯操作的同學(xué)提供一個(gè)在線反編譯工具:http://www.javadecompilers.com/
import about_proxy.dynamic_proxy.Subject;
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 Subject
{
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public $Proxy0(InvocationHandler paramInvocationHandler)
{
super(paramInvocationHandler);
}
public final boolean equals(Object paramObject)
{
try
{
return ((Boolean)h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final void doSomething()
{
try
{
h.invoke(this, m3, null);
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final String toString()
{
try
{
return (String)h.invoke(this, m2, null);
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final int hashCode()
{
try
{
return ((Integer)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") });
m3 = Class.forName("about_proxy.dynamic_proxy.Subject").getMethod("doSomething", 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]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
}
我們先來看該類的構(gòu)造方法
public $Proxy0(InvocationHandler paramInvocationHandler)
{
super(paramInvocationHandler);
}
傳入?yún)?shù)為InvocationHandler卵凑,這就是為什么動(dòng)態(tài)代理類在調(diào)用接口中方法時(shí)會(huì)走到自定義的InvocationHandler中的invoke方法。
super(paramInvocationHandler)胜臊,是調(diào)用父類Proxy的構(gòu)造方法勺卢。而父類又持有protected InvocationHandler h的實(shí)例,參考Proxy的構(gòu)造方法:
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
在繼續(xù)看反編譯出來文件的靜態(tài)代碼塊
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
m3 = Class.forName("about_proxy.dynamic_proxy.Subject").getMethod("doSomething", 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]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
我們?cè)诮涌谥卸x的方法doSomething通過反射得到的名字是m3象对,我們繼續(xù)查看文件中實(shí)現(xiàn)的doSomething()方法
public final void doSomething()
{
try
{
h.invoke(this, m3, null);
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
這里調(diào)用代理對(duì)象的doSomething方法黑忱,直接就調(diào)用了InvocationHandler中的invoke方法,并把m3傳了進(jìn)去织盼。
this.h.invoke(this, m3, null);
其余的equals杨何、toString、hashCode也是同樣的道理沥邻。
到這里就很明了了危虱,所有的動(dòng)態(tài)代理流程也清晰了。
五唐全、總結(jié)
JDK是動(dòng)態(tài)生成代理類埃跷,并通過調(diào)用解析器蕊玷,執(zhí)行接口實(shí)現(xiàn)的方法的原理已經(jīng)一目了然。動(dòng)態(tài)代理加上反射弥雹,是很多框架的基礎(chǔ)垃帅。期待下一章節(jié)實(shí)現(xiàn)根據(jù)動(dòng)態(tài)代理與反射實(shí)現(xiàn)的android的注入框架原理解析。
個(gè)人見解剪勿,若有錯(cuò)誤之處贸诚,歡迎指出更正
文章中demo放置在github
https://github.com/loosaSH/java-Proxy
參考文章:
1、Java帝國之動(dòng)態(tài)代理(用故事形式講解動(dòng)態(tài)代理的出現(xiàn)及原理)
2厕吉、知乎-Java 動(dòng)態(tài)代理作用是什么酱固?
3、簡書-動(dòng)態(tài)代理
4头朱、JDK8動(dòng)態(tài)代理源碼分析