標(biāo)簽: java
Contents
代理是實(shí)現(xiàn)AOP(Aspect oriented program祭示,面向切面編程)的核心和關(guān)鍵技術(shù)胀糜。
概念
代理是一種設(shè)計(jì)模式烤镐,其目的是為其他對象提供一個代理以控制對某個對象的訪問粥航,代理類負(fù)責(zé)為委托類預(yù)處理消息舀奶,過濾消息并轉(zhuǎn)發(fā)消息以及進(jìn)行消息被委托類執(zhí)行后的后續(xù)處理。為了保持行為的一致性碌宴,代理類和委托類通常會實(shí)現(xiàn)相同的接口
- 靜態(tài)代理:由程序員創(chuàng)建代理類或特定工具自動生成源代碼再對其編譯页慷,也就是說在程序運(yùn)行前代理類的.class文件就已經(jīng)存在。
- 動態(tài)代理:在程序運(yùn)行時運(yùn)用反射機(jī)制動態(tài)創(chuàng)建生成执庐。
紫色箭頭代表類的繼承關(guān)系酪耕,紅色連線表示調(diào)用關(guān)系
動態(tài)代理
- JVM可以在運(yùn)行期動態(tài)生成類的字節(jié)碼,該類往往被用作動態(tài)代理類轨淌。
- JVM生成的動態(tài)類必須實(shí)現(xiàn)一個或多個接口迂烁,所以這種只能用作具有相同接口的目標(biāo)類的代理。
- CGLIB庫可以動態(tài)生成一個類的子類递鹉,一個類的子類也可作為該類的代理盟步,這個可用來為沒有實(shí)現(xiàn)接口的類生成動態(tài)代理類。
- 代理類可在調(diào)用目標(biāo)方法之前躏结、之后却盘、前后、以及處理目標(biāo)方法異常的catch塊中添加系統(tǒng)功能代碼媳拴。
創(chuàng)建動態(tài)類
API:
java.lang.reflect:Class Proxy
java.lang.reflect:Interface InvocationHandler
- 查看代理類方法列表信息
package com.iot.proxy;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by brian on 2015/12/27.
*/
public class ProxyTest {
public static void main(String[] args) throws Exception {
Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
System.out.println(clazzProxy1);
printConstructors(clazzProxy1);
printMethods(clazzProxy1);
}
/**
* 打印構(gòu)造方法列表
* @param clazz
*/
public static void printConstructors(Class clazz){
System.out.println("-------------constructors list-------------");
Constructor[] constructors = clazz.getConstructors();
System.out.print(getExecutableList(constructors));
}
/**
* 打印成員方法列表
* @param clazz
*/
public static void printMethods(Class clazz) {
System.out.println("-------------methods list-------------");
Method[] methods = clazz.getMethods();
System.out.print(getExecutableList(methods));
}
/**
* 獲取要打印的列表數(shù)據(jù)
* 每行一個方法,按照func(arg1,arg2)的格式
* @param executables
* @return
*/
public static String getExecutableList(Executable[] executables){
StringBuilder stringBuilder = new StringBuilder();
for (Executable executable : executables) {
String name = executable.getName();
stringBuilder.append(name);
stringBuilder.append("(");
Class[] clazzParams = executable.getParameterTypes();
for (Class clazzParam : clazzParams) {
stringBuilder.append(clazzParam.getName()).append(",");
}
if (clazzParams != null && clazzParams.length != 0) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
stringBuilder.append(")\n");
}
return stringBuilder.toString();
}
}
輸出結(jié)果:
class com.sun.proxy.$Proxy0
-------------constructors list-------------
com.sun.proxy.$Proxy0(java.lang.reflect.InvocationHandler)
-------------methods list-------------
add(java.lang.Object)
remove(java.lang.Object)
equals(java.lang.Object)
toString()
hashCode()
clear()
contains(java.lang.Object)
isEmpty()
iterator()
size()
toArray([Ljava.lang.Object;)
toArray()
spliterator()
addAll(java.util.Collection)
stream()
forEach(java.util.function.Consumer)
containsAll(java.util.Collection)
removeAll(java.util.Collection)
removeIf(java.util.function.Predicate)
retainAll(java.util.Collection)
parallelStream()
isProxyClass(java.lang.Class)
getInvocationHandler(java.lang.Object)
getProxyClass(java.lang.ClassLoader,[Ljava.lang.Class;)
newProxyInstance(java.lang.ClassLoader,[Ljava.lang.Class;,java.lang.reflect.InvocationHandler)
wait()
wait(long,int)
wait(long)
getClass()
notify()
notifyAll()
- 創(chuàng)建實(shí)例對象
/**
* 測試創(chuàng)建實(shí)例對象
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
*/
private static void createProxyInstance( ) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
/**
* 方法1:先創(chuàng)建代理類黄橘,再使用反射創(chuàng)建實(shí)例對象
*/
Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
Collection proxy1 = (Collection) constructor.newInstance(new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return null;
}
});
/**
* 方法2:直接使用newProxyInstance方法創(chuàng)建實(shí)例對象
*/
Collection proxy2 = (Collection)Proxy.newProxyInstance(
Collection.class.getClassLoader(),
new Class[]{Collection.class},
new InvocationHandler() {
ArrayList target = new ArrayList();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//ArrayList targetTmp = new ArrayList();
System.out.println("before invoke method: "+method.getName());
return method.invoke(target,args);
}
});
proxy2.add("aaa");
proxy2.add("bbb");
System.out.println(proxy2.size());
System.out.println(proxy2);
System.out.println(proxy2.getClass().getName());
}
輸出結(jié)果:
before invoke method: add
before invoke method: add
before invoke method: size
2
before invoke method: toString
[aaa, bbb]
com.sun.proxy.$Proxy0
上述代碼相關(guān)說明:
- 若將
method.invoke(target,args);
改為method.invoke(proxy,args);
會出現(xiàn)死循環(huán) - 從輸出結(jié)果可知,每次調(diào)用代理類的方法屈溉,實(shí)際都是調(diào)用
invoke
方法 - 若將
method.invoke(target,args);
改為method.invoke(targetTmp,args);
塞关,則proxy2.size()
為0。因?yàn)槊看握{(diào)用invoke
方法時子巾,targetTmp
為新的局部變量 -
Object
類只有的hashCode
,equals
, ortoString
方法會被交到InvocationHandler
帆赢,其他方法自己有實(shí)現(xiàn),不交給handler,所以最后打印結(jié)果為com.sun.proxy.$Proxy0
而不是Collection
-
InvocationHandler
對象的運(yùn)行原理**
InvocationHandler
接口只有一個invoke
方法线梗,每次調(diào)用代理類的方法匿醒,即調(diào)用了InvocationHandler
對象的invoke
方法
invoke
方法涉及三個要素:
- 代理對象
- 代理對象調(diào)用的方法
- 方法接受的參數(shù)
注:Object類的hashCode
,equals
,toString
方法交給invoke,其他的Object類的方法,Proxy有自己的實(shí)現(xiàn)缠导。
If a proxy interface contains a method with the same name and parameter signature as the hashCode, equals, or toString methods of java.lang.Object, when such a method is invoked on a proxy instance, the Method object passed to the invocation handler will have java.lang.Object as its declaring class. In other words, the public, non-final methods of java.lang.Object logically precede all of the proxy interfaces for the determination of which Method object to pass to the invocation handler.
動態(tài)代理的工作原理
代理類創(chuàng)建時需要傳入一個InvocationHandler對象廉羔,client調(diào)用代理類,代理類的相應(yīng)方法調(diào)用InvocationHandler的的invoke方法僻造,InvocationHandler的invoke方法(可在其中加入日志記錄憋他、時間統(tǒng)計(jì)等附加功能)再找目標(biāo)類的相應(yīng)方法。
面向切面編程
把切面的代碼以對象的形式傳遞給InvocationHandler的invoke方法髓削,invoke方法中執(zhí)行該對象的方法就執(zhí)行了切面的代碼竹挡。
所以需要傳遞兩個參數(shù):
1.目標(biāo)(Object target)
2.通知(自定義的adviser類)
定義Advice
接口
public interface Advice {
void beforeMethod(Method method);
void aftereMethod(Method method);
}
一個實(shí)現(xiàn)Advice
接口的類MyAdvice
,用于打印執(zhí)行方法前和執(zhí)行后的時間
import java.lang.reflect.Method;
public class MyAdvice implements Advice{
long beginTime = 0 ;
@Override
public void beforeMethod(Method method) {
System.out.println(method.getName()+" before at "+beginTime);
beginTime = System.currentTimeMillis();
}
@Override
public void aftereMethod(Method method) {
long endTime = System.currentTimeMillis();
System.out.println(method.getName()+" cost total "+ (endTime-beginTime));
}
}
定義一個getProxy
方法創(chuàng)建實(shí)例對象,接收兩個參數(shù):目標(biāo)和通知
private static Object getProxy(final Object target,final Advice advice){
Object proxy = Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
advice.beforeMethod(method);
Object retVal = method.invoke(target,args);
advice.aftereMethod(method);
return retVal;
}
}
);
return proxy;
}
調(diào)用:
Collection proxy3 = (Collection) getProxy(new ArrayList(),new MyAdvice());
proxy3.add("111");
proxy3.add("222");
System.out.println(proxy3.size());
輸出:
add before at 0
add cost total 0
add before at 1454433980839
add cost total 0
size before at 1454433980839
size cost total 0
2
參考資料
作者@brianway更多文章:個人網(wǎng)站 | CSDN | oschina