package com.czp.util; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * 代理生成工厂,要求其子类实现before(...),after(...),onException(...) 实现处理业务 * * @author caozhongping * */ public abstract class ProxyFacty<T> implements InvocationHandler { private T target; public ProxyFacty(T target) { super(); this.target = target; } /** * 创建代理,如果目标类没有实现接口则返回自己 * * @param target * @return */ @SuppressWarnings("unchecked") public T getProxy() { Class<T> cls = (Class<T>) target.getClass(); if (cls.getInterfaces() != null) { return (T) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), this); } return target; } /*** * 通过代理实现调用 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object obj = null; try { before(args); obj = method.invoke(target, args); after(args); } catch (Exception e) { onException(e); } return obj; } /*** * 出现异常时处理 * * @param ex */ public abstract void onException(Exception ex); /** * 调用方法后处理 * * @param args */ public abstract void after(Object[] args); /** * 调用方法前处理 * * @param args */ public abstract void before(Object[] args); } //目标对象的接口 package com.czp.util; public interface TestItf { void say(String name)throws Exception; } //目标对象 package com.czp.util; public class TestItfImpl implements TestItf { @Override public void say(String name) throws Exception { if(name==null) throw new Exception("name is null"); System.out.println("Hell, "+name); } } //代理工具类,继承工厂类实现拦截 package com.czp.util; public class ProxyUtil<T> extends ProxyFacty<T>{ public ProxyUtil(T target) { super(target); } @Override public void onException(Exception ex) { System.out.println("call Method error:"+ex); } @Override public void after(Object[] args) { System.out.println("----------exit method-----------"); } @Override public void before(Object[] args) { System.out.println("-----Enter method------"); } public static void main(String[] args) throws Exception { TestItf target = new TestItfImpl();//目标对象 TestItf proxy = new ProxyUtil<TestItf>(target).getProxy();//目标的代理实例 proxy.say("WengJiaBao");//正常调用 //异常调用 proxy.say(null); } } //输出: -----Enter method------ Hell, WengJiaBao ----------exit method----------- -----Enter method------ call Method error:java.lang.reflect.InvocationTargetException