標籤:one row static ide rgs tproxy -- tin ant
首先我們定義一個介面
public interface SayService { public void say();}View Code
接著實現這個介面
public class SayImpl implements SayService { @Override public void say() { System.out.println("I want to go shoping."); }}View Code
定義一個動態代理類了,每一個動態代理類都必須要實現 InvocationHandler 這個介面
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class DynamicProxy implements InvocationHandler { //我們要代理的真實對象 private Object object; public DynamicProxy(Object object) { this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before go shoping"); //當代理對象調用真實對象的方法時,其會自動跳轉到代理對象關聯的handler對象的invoke方法進行調用 method.invoke(object, args); System.out.println("after go shoping"); return null; }}View Code
定義測試方法
public class TestProxy { public static void main(String[] args) { //要代理的對象 SayService sayImpl = new SayImpl(); //要代理哪個對象,就要將改對象傳進去,最後是通過其真實對象來調用方法的 InvocationHandler handler = new DynamicProxy(sayImpl); //Proxy.newProxyInstance--建立代理對象 //handler.getClass().getClassLoader()---載入代理對象 //sayImpl.getClass().getInterfaces()--為代理對象提供的介面是真實對象所實現的介面,表示我們要代理的是改真實對象,這樣我們就能調用介面中的方法 //handler-關聯上的InvocationHandler這個對象 SayService sayService = (SayService)Proxy.newProxyInstance(handler.getClass().getClassLoader() ,sayImpl.getClass().getInterfaces(), handler); sayService.say(); }}View Code
控制台列印的日誌
before go shoping
I want to go shoping.
after go shoping
Java動態代理