代理 aop

Porxy.newProxyInstance(Object target,Class<?>[] Interfaces,InvocationHandler args);

三个参数的定义:target表示代理的目标类
                     Interfaces表示代理目标类实现的接口
                     InvocationHandler  aop编写的地方 这是一个interface,有一个invoke 的方法!                  
     例如:

       public static Object getProxy(Object target, Advice advice) {

InvocationHandler invocationHandler = new MyInvcationHandler(advice,
target);
Object proxy = Proxy.newProxyInstance(target.getClass()
.getClassLoader(), target.getClass().getInterfaces(),
invocationHandler);
return proxy;
}



package fat.yk.test2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;

public class MyInvcationHandler implements InvocationHandler {

private Advice advice = null;
private Object target = null;

public MyInvcationHandler(Advice advice, Object target) {
this.advice = advice;
this.target = target;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
this.advice.beforeMethod();
System.out.println("proxy:" + proxy.getClass().getName());
Object retVal = method.invoke(this.target, args);//回调目标方法
this.advice.afterMethod();
return retVal;
}

}
具体代码如如下:
main函数:  ProxyTest类
              

你可能感兴趣的:(java,AOP)