在java中提供了一個動態代理類,這個類位於java.lang.reflect包中的Proxy類中。什么是動態代理類呢?就是可以在運行時創建一個實現了一組給定接口的新類。聽上去有點高深的樣子,其實是提供了一種類的包裝器,最終對接口中方法的調用還是由現有的接口的實現類去調用。
比如,現在有一個ArrayList的對象,可以向其中添加任意的string對象,但是我們不需要添加apple這個字符串。ArrayList默認是不會提供這種字符串過濾的方法的,這個時候我們就可以使用Proxy代理類,在這個類中我們添加字符串的過濾規則,然后決定當前的字符串是否可以被添加到ArrayList中去。
Proxy類中提供了一個方便的static方法用來構造proxy對象。Proxy.newProxyInstance(ClassLoader ,Class<?>[] interfaces, Invocationhandler).
參數classLoader:類的加載器,使用null表示使用默認的加載器。
參數 interfaces:需要代理的接口數組。
invocationHandler:調用處理器,使用新建的proxy對象調用方法的時候,都會調用到該接口中的invoke方法。
1 package com.app.myinterface; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.lang.reflect.Proxy; 6 import java.util.ArrayList; 7 import java.util.List; 8 9 /** 10 * Created by Charles on 2015/11/2. 11 */ 12 public class ProxyMotion { 13 14 public static void main(String args[]) { 15 16 ArrayList<String> content = new ArrayList<String>(); 17 MyInvocationHandler handler = new MyInvocationHandler(content); 18 Object proxy = Proxy.newProxyInstance(null, new Class[]{List.class}, handler); 19 if(proxy instanceof List){ //判斷當前的proxy對象是否是List接口 20 System.out.println("proxy is list"); 21 List<String> mlist = (List<String>)proxy; 22 mlist.add("one"); 23 mlist.add("two"); 24 mlist.add("three"); 25 mlist.add("apple"); 26 } 27 System.out.println("proxy:"+proxy.toString()); 28 System.out.println("content:"+content.toString()); 29 } 30 31 } 32 class MyInvocationHandler implements InvocationHandler { 33 //具體的調用類 34 Object target; 35 36 public MyInvocationHandler(Object obj) { 37 target = obj; 38 } 39 40 @Override 41 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 42 //當前所持有的proxy對象 43 //method表示當前別調用的方法 44 //args表示方法中傳遞的參數 45 System.out.println("method name:"+method.getName()); 46 if(method.getName().equals("add")){ 47 if(args[0].equals("apple")){ 48 return false; 49 } 50 } 51 return method.invoke(target, args); 52 } 53 }
調用結果:
proxy is list
method name:add
method name:add
method name:add
method name:add
method name:toString
proxy:[one, two, three]
content:[one, two, three]
這樣,使用Proxy我們就輕松的為ArrayList添加了一個過濾規則。使用Proxy還有很多的好處,比如對於方法的調用堆棧等等。
