java 動態代理proxy類使用
阿新 • • 發佈:2018-12-18
此模式一般用在不修改原始碼的情況下對類進行增強。
一下給出簡單的使用方法詳見程式碼:
- 介面與實現類
package test; /** * person介面 * @author Administrator * */ public interface Person { public void say(); } package test; /** * person實現類 * @author Administrator * */ public class PersonImpl implements Person{ @Override public void say() { System.out.println("hello!"); } }
獲得代理的工具類
package test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * #演示代理的工具類 * @author Administrator * */ public class ProxyUtils { /** * #獲取person類的代理的工具 * @param person 可以是介面的任意實現類 * @return */ public static Person getProxy(final Person person) { /* * #使用java.lang.reflect.Proxy獲得代理 * #引數1:代理介面的classloader * #引數2:代理介面的interface * #引數3:InvocationHandler的實現類或內部類,本例使用內部類實現。 * #強轉為返回的型別 */ Person proxy = (Person) Proxy.newProxyInstance(person.getClass().getClassLoader(), person.getClass().getInterfaces(), new InvocationHandler() { /* * #引數1不要使用 * #引數2是proxy呼叫的實現類的方法 * #引數3是方法的引數 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //在invoke前執行的方法,可以使記錄日誌等。。。 System.out.println("執行" + method.getName() + "前。"); //執行proxy呼叫的實現類的方法 method.invoke(person, args); //在invoke後執行的方法,可以使記錄日誌等。。。 System.out.println("執行" + method.getName() + "後。"); return null; } }); //返回該代理 return proxy; } }
測試類
package test;
import org.junit.Test;
/**
* #代理模式的測試類
* @author Administrator
*
*/
public class DemoProxy {
@Test
public void run() {
//通過proxyUtils獲得需代理的類
Person proxy = ProxyUtils.getProxy(new PersonImpl());
//執行該類的方法
proxy.say();
}
}
執行結果: