標籤:AC load [] return handle span targe row 傳遞
一介面和實作類別
interface Subject { public void hello();}class RealSubject implements Subject { @Override public void hello() { System.out.println("hello"); }}
二、建立代理實作類別
class DynamicProxy implements InvocationHandler { // 代理的真實對象 private Object target; public DynamicProxy(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("beffor"); // 當代理對象調用真實對象的方法時,其會自動執行代理對象關聯的handler對象的invoke方法來進行調用, // 無論何時調用代理對象的方法,調用處理器的 invoke 方法都會被調用, 並向其傳遞Method 對象和原始的調用參數。 調用處理器必須給出處理調用的方式 method.invoke(target, args); System.out.println("affter"); return null; }}
三、測試代碼
class ProxyTest { public static void main(String[] args) { Subject realSubject = new RealSubject(); InvocationHandler invocationHandler = new DynamicProxy(realSubject); /* * 通過Proxy的newProxyInstance方法來建立我們的代理對象,我們來看看其三個參數 * 第一個參數 類載入器 handler.getClass().getClassLoader() ,我們這裡使用realSubject這個類的ClassLoader對象來載入我們的代理對象 * 第二個參數 一個class對象數組,每個元素都要實現的介面。我們這裡為代理對象提供的介面是真實對象所實行的介面,表示我要代理的是該真實對象,這樣我就能調用這組介面中的方法了 * 第三個參數 一個調用處理器 invocationHandler, 我們這裡將這個代理對象關聯到了上方的 InvocationHandler 這個對象上 * */ Subject proxy = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), invocationHandler); proxy.hello(); //realSubject.hello(); }}
java動態代理