import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; //代理需要實現的介面 interface IVehical {
//例如我這裡寫了兩個介面 void run(); void say(); } //concrete implementation class Car implements IVehical{ //下面這兩個方法,作為介面的實現方法,如果介面中沒有這些方法,而在這裡出現了多餘的方法程式將編譯不過。 //每次調用這兩個方法都會觸發代理對象中的invoke方法。 public void run() { System.out.println("Car is running"); } public void say() { System.out.println("just one!"); } } //proxy class //這個類是用來建立代理對象的,這裡只是對它進行了簡單的封裝 class VehicalProxy { private IVehical vehical; public VehicalProxy(IVehical vehical) { this.vehical = vehical; } //這個方法返回建立後的對象代理 public IVehical create(){ final Class<?>[] interfaces = new Class[]{IVehical.class}; final VehicalInvacationHandler handler = new VehicalInvacationHandler(vehical); return (IVehical) Proxy.newProxyInstance(IVehical.class.getClassLoader(), interfaces, (InvocationHandler) handler); } //這個是跟代理對象綁定的一個處理器,www.111cn.net每次調用對象代理中的方法都會觸發這個處理器中的invoke方法 class VehicalInvacationHandler implements InvocationHandler{ private final IVehical vehical; public VehicalInvacationHandler(IVehical vehical) { this.vehical = vehical; } //每當執行對象代理的say或者call(只要是IVehical介面中的方法)就會觸發invoke被執行 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("--before running..."); Object ret = method.invoke(vehical, args); System.out.println("--after running..."); return ret; } } } class Main { public static void main(String[] args) { IVehical car = new Car(); VehicalProxy proxy = new VehicalProxy(car); IVehical proxyObj = proxy.create(); proxyObj.say(); } } |