看了smart-framework,写一下自己对代理的理解 话不多说,直接上代码
public interface Proxy{
public Object doProxy(ProxyChain proxyChain);
}
public class ProxyImpl implements Proxy{
public Object doProxy(ProxyChain proxyChain){
Object result= null;
//before
result = proxyChain.doProxyChain();
//after
}
}
public class ProxyChain{
private List<Proxy> proxys;
private MethodProxy methodProxy;
private Class<?> targetClass;
private Object targetObject;
private Method targetMethod;
private Object[] methodParams;
private int proxyIndex = 0;
public ProxyChain(Class<?> targetClass,Object targetObject,Method targetMethod,Object[] methodParams,methodProxy,List<Proxy> proxys){
......
}
public Object doProxyChain(){
Object result = null;
if(proxyIndex<proxys.size()){
result = proxys.get(proxyIndex++).doProxy(this);
}else{
result = methodProxy.invokeSuper(targetObj,methodParams);
}
return result;
}
}
public class ProxyManager{
public static <T> T createProxy(Class<?> targetClass,List<Proxy> proxys){
return (T) Enhancer.create(targetClass,new MethodInterceptor(){
public Object interceptor(Object targetObject, Method targetMethod, Object[] methodParams,MethodProxy methodProxy){
return new ProxyChain(targetClass,targetObject,targetMethod,methodParams,methodProxy,proxys).doProxyChain();
}
});
}
}
在ProxyManager中得到代理对象
在ProxyChain可以用做链路处理
proxy的子类中就可以进行相似于spring中的Aspect进行切面处理了