在after advice中访问类成员以执行切入点

时间:2013-07-18 14:04:19

标签: java aop aspectj

我试图在下面的示例代码中执行readObject()后获取read String的值,该建议代码建议readObject()连接点。

public class Eg {

    private ObjectOutputStream output;
    private ObjectInputStream input;
    Public String request="";

    public Eg(File source){
            output; // output stream to client
            input= new ObjectInputStream( file ); 
        }

    public void method() {
            try{            
                while(true) {
                    request =(String) input.readObject();
                    //do something with request
                }//while
            }
            catch (IOException ex) 
            {
                ex.printStackTrace();
            } 
    }

}

和我的方面:

public aspect ReadStringGetter {
    public pointcut readOperation() :
      execution(* java.io.ObjectInputStream.readObject());

    after() : readOperation() {
        Eg eg = (Eg) thisJoinPoint.getThis();
        System.out.println(eg.request);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用this切入点来获取连接点的上下文(Eg的实例):

class Eg {
    public String request = "";
    public void method() {
        request = "xy";
        System.out.println(request);
    }
}

呼叫者:

Eg c = new Eg();
c.method();

方面:

public aspect MyAspect {

    pointcut EgMethodsExecution(Eg eg) : 
        execution(* Eg.method(..)) && this(eg);

    after(Eg eg) : EgMethodsExecution(eg) {
        System.out.println("~ in aspect ~ " + eg.request);
    }

}

输出:

  

XY
  〜在方面~xy