使用JDK 1.5 中自带的Proxy代理类,可以模仿出Spring AOP的简易模型,仅能对实现的接口(任何)的类的方法进行拦截。
代码如下:
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy;
/** * AOP类 实现的拦截接口 * @author eMavaj * */ public class MyAOP implements InvocationHandler{ /** * 创建动态代理 把对象的调用用InvocationHandler拦截下,委派给代理(自身) * @param tag * @return */ public Object createAOP(Object tag){ Object temp = Proxy.newProxyInstance( this.getClass().getClassLoader(), tag.getClass().getInterfaces(), this ); return temp; } /** * 接口方法,拦截之后回调的拦截处理函数 */ public Object invoke(Object tag, Method method, Object[] arg2) throws Throwable { /** * 拦截处理 */ if(Isright(tag)){ /** * 下一层拦截处理 */ Object temp = method.invoke(tag, arg2); return temp; } return null; } private boolean Isright(Object tag){ //do something return false; } }
呵呵,学好Java反射,自己写框架玩玩哦~
|