动态代理简单代码
/** * 业务接口 */ public interface Subject { void call(); }
/** * 业务接口的实现(被代理的类) */ public class RealSubjcet implements Subject { @Override public void call() { Log.d("denny", "RealSubject#call"); } }
/** * 代理类 */ public class ProxyHandler implements InvocationHandler { private final Object realSubject; public ProxyHandler(Object realSubject) { this.realSubject = realSubject; } @Override public Object invoke(Object o, Method method, Object[] args) throws Throwable { Log.d("denny", "before ProxyHandler#invoke"); Object result = method.invoke(realSubject, args); Log.d("denny", "after ProxyHandler#invoke"); return result; } }
// 通过Proxy创建代理类对象 RealSubjcet realSubjcet = new RealSubjcet(); Subject proxySubject = (Subject) Proxy.newProxyInstance( Subject.class.getClassLoader(), new Class[]{Subject.class}, new ProxyHandler(realSubjcet)); proxySubject.call();
以及,最终的结果:
D/denny: before ProxyHandler#invoke
D/denny: RealSubject#call
D/denny: after ProxyHandler#invoke