所有动态代理其实是利用反射机制的基础,反射调用代理对象delegate的方法时,我们可以在调用前和调用后实现自己的作用代码,达到动态给原有方法增加功能的目的,好吧闲话少说直接上代码:
private DynamicMethod mDynamicMethod; private Object mDelegate; public QxInvocationHandler(Object delegate) { this.mDelegate = delegate; } public QxInvocationHandler(Object delegate, DynamicMethod dynamicMethod) { this.mDelegate = delegate; this.mDynamicMethod = dynamicMethod; } public Object bind() { return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), mDelegate.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object obj = null; if (mDynamicMethod != null) { mDynamicMethod.beforeInvokeMothed(); } obj = method.invoke(mDelegate, args); if (mDynamicMethod != null) { mDynamicMethod.afterInvokeMehod(); } return obj; } public void setmDynamicMethod(DynamicMethod mDynamicMethod) { this.mDynamicMethod = mDynamicMethod; } public interface DynamicMethod { void beforeInvokeMothed(); void afterInvokeMehod(); }