標籤: javahtml
[TOC]java
#代理 代理是實現AOP(Aspect oriented program,面向編程)的核心和關鍵技術。git
代理是一種設計模式,其目的是爲其餘對象提供一個代理以控制對某個對象的訪問,代理類負責爲委託類預處理消息,過濾消息並轉發消息以及進行消息被委託類執行後的後續處理。爲了保持行爲的一致性,代理類和委託類一般會實現相同的接口程序員
紫色箭頭表明類的繼承關係,紅色連線表示調用關係github
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); } /** * 打印構造方法列表 * @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)); } /** * 獲取要打印的列表數據 * 每行一個方法,按照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(); } }
輸出結果:api
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()
/** * 測試建立實例對象 * @throws NoSuchMethodException * @throws IllegalAccessException * @throws InvocationTargetException * @throws InstantiationException */ private static void createProxyInstance( ) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { /** * 方法1:先建立代理類,再使用反射建立實例對象 */ 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方法建立實例對象 */ 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()); }
輸出結果:架構
before invoke method: add before invoke method: add before invoke method: size 2 before invoke method: toString [aaa, bbb] com.sun.proxy.$Proxy0
上述代碼相關說明:oracle
若將method.invoke(target,args);
改成method.invoke(proxy,args);
會出現死循環
從輸出結果可知,每次調用代理類的方法,實際都是調用invoke
方法
若將method.invoke(target,args);
改成method.invoke(targetTmp,args);
,則proxy2.size()
爲0。由於每次調用invoke
方法時,targetTmp
爲新的局部變量
Object
類只有的hashCode
, equals
, or toString
方法會被交到InvocationHandler
,其餘方法本身有實現,不交給handler,因此最後打印結果爲com.sun.proxy.$Proxy0
而不是Collection
InvocationHandler
對象的運行原理**
InvocationHandler
接口只有一個invoke
方法,每次調用代理類的方法,即調用了InvocationHandler
對象的invoke
方法
invoke
方法涉及三個要素:
注:Object類的hashCode
,equals
,toString
方法交給invoke,其餘的Object類的方法,Proxy有本身的實現。
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.
代理類建立時須要傳入一個InvocationHandler對象,client調用代理類,代理類的相應方法調用InvocationHandler的的invoke方法,InvocationHandler的的invoke方法(可在其中加入日誌記錄、時間統計等附加功能)再找目標類的相應方法。
把切面的代碼以對象的形式傳遞給InvocationHandler的的invoke方法,invoke方法中執行該對象的方法就執行了切面的代碼。
因此須要傳遞兩個參數:
1.目標(Object target) 2.通知(自定義的adviser類)
定義Advice
接口
public interface Advice { void beforeMethod(Method method); void aftereMethod(Method method); }
一個實現Advice
接口的類MyAdvice
,用於打印執行方法前和執行後的時間
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
方法建立實例對象,接收兩個參數:目標和通知
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; }
調用:
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