給ArrayList寫個代理,實現方法過濾
阿新 • • 發佈:2019-01-26
public class ArraryListProxy { List list = new ArrayList(); public List getProxy(){ return (List)Proxy.newProxyInstance(ArrayList.class.getClassLoader(), ArrayList.class.getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.toString().contains("remove")) { System.err.println("抱歉,你不能使用"+method.getName()+"方法"); return null; } Object obj = method.invoke(list, args); return obj; } }); } } class TestProxy{ public static void main(String[] args) { ArraryListProxy proxy = new ArraryListProxy(); List listProxy = proxy.getProxy(); listProxy.add("Tom"); listProxy.add("Jack"); listProxy.add("Bety"); System.out.println(listProxy); listProxy.remove(2);//1 System.out.println(listProxy);//2 } }
輸出結果:
代理的執行過程:先通過Proxy的靜態方法newProxyInstance生成代理物件,然後呼叫代理物件的add方法,呼叫InvocationHandler物件的invoke方法,通過反射呼叫真實物件的add方法。
存在的問題:程式碼中1和2處的執行順序不是固定的,有待繼續研究。