java 代理機(jī)制的實(shí)例詳解
前言:
java代理分靜態(tài)代理和動(dòng)態(tài)代理,動(dòng)態(tài)代理有jdk代理和cglib代理兩種,在運(yùn)行時(shí)生成新的子類class文件。本文主要練習(xí)下動(dòng)態(tài)代理,代碼用于備忘。對(duì)于代理的原理和機(jī)制,網(wǎng)上有很多寫的很好的,就不班門弄斧了。
jdk代理
實(shí)例代碼
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFactory implements InvocationHandler { private Object tarjectObject; public Object creatProxyInstance(Object obj) { this.tarjectObject = obj; return Proxy.newProxyInstance(this.tarjectObject.getClass() .getClassLoader(), this.tarjectObject.getClass() .getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; if (AssessUtils.isAssess()) { result = method.invoke(this.tarjectObject, args); }else{ throw new NoAssessException("This server cannot run this service."); } return result; } }