动态代理Proxy的递归

由java.lang.reflect.Proxy得到的动态代理类实例依然是一个Proxy
现在我写两个Handler来实现不同的切面功能: handler_1 和handler_2
看如下代码:
1 接口
public interface IService {

    void foo();
}


2 实现
public class ServiceImpl implements IService{

    public void foo() {
        System.out.println("Business really goes here");
    }

}


3 切面
public class handler_1 implements InvocationHandler {

    private Object stub;

    public handler_1(Object stub) {
        this.stub = stub;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        System.out.println("before handler_1");
        method.invoke(stub, args);
        System.out.println("after handler_1");
        return result;
    }
}


public class handler_2 implements InvocationHandler {

    private Object stub;

    public handler_2(Object stub) {
        this.stub = stub;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        System.out.println("before handler_2");
        method.invoke(stub, args);
        System.out.println("after handler_2");
        return result;
    }
}


4 客户代码
  public static void main(String[] args) {
        // TODO code application logic here
        ServiceImpl si = new ServiceImpl();
        handler_1 h1 = new handler_1(si);
        handler_2 h2 = new handler_2(si);

        Proxy p1 = (Proxy) Proxy.newProxyInstance(IService.class.getClassLoader(), new Class[]{IService.class}, h1);
        //利用得到的p1代理实例来获取第二个实例,并指定其处理程序为h2
        @SuppressWarnings("static-access")
        Proxy p2 = (Proxy) p1.newProxyInstance(IService.class.getClassLoader(), new Class[]{IService.class}, h2);

        IService service_1 = (IService) p1;
        IService service_2 = (IService) p2;
        service_1.foo();
        service_2.foo();

    }


Guess what,最终得到的这个p_2的动态代理实例到底采用的那个handler切面呢? 是h2的还是h1+h2的?
引用
init:
deps-jar:
Compiling 1 source file to F:\aop\build\classes
compile:
run:
before handler_1
Business really goes here
after handler_1
before handler_2
Business really goes here
after handler_2
成功生成(总时间:0 秒)


可以使用如下方法:
引用
        IService service= (IService) Proxy.newProxyInstance(IService.class.getClassLoader(), new Class[]{IService.class}, h1);
        IService service= (IService) Proxy.newProxyInstance(IService.class.getClassLoader(), new Class[]{IService.class}, service);



你可能感兴趣的:(spring,AOP,servlet,F#,Access)