動態代理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的?
[quote]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 秒)
[/quote]

可以使用如下方法:
[quote] 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);[/quote]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章