Recipe 4.5. Capturing the Value of the this Reference When a Method Is ExecutingProblemWhen capturing a method during execution, you want to expose the object pointed to by the Java this reference so it can be used by your advice. SolutionCreate a pointcut that specifies a single parameter of the same type as the this reference you want to capture. Use the execution(Signature) and this(Type | Identifier) pointcuts to capture the execution of a method and then to bind the single identifier to the object that the this reference points to during the method's execution. DiscussionExample 4-5 shows the execution(Signature) pointcut being used to declare an interest in all methods that match the signature MyClass.foo(int,String). The captureThisDuringExecution(MyClass) pointcut requires a MyClass object as specified by the myObject identifier. The myObject identifier is then bound to the methods this reference by the this(Type | Identifier) pointcut. Example 4-5. Capturing the this reference during the execution of the MyClass.foo(..) methodpublic aspect CaptureThisReferenceRecipe { /* Specifies calling advice whenever a method matching the following rules gets executed: Class Name: MyClass Method Name: foo Method Return Type: void Method Parameters: an int followed by a String */ pointcut captureThisDuringExecution(MyClass myObject) : execution(void MyClass.foo(int, String)) && this(myObject); // Advice declaration before(MyClass myObject) : captureThisDuringExecution(myObject) { System.out.println( "------------------- Aspect Advice Logic --------------------"); System.out.println( "In the advice attached to the execution point cut"); System.out.println("Captured this reference: " + myObject); System.out.println( "------------------------------------------------------------"); } } The before( ) advice can access the identifier that references the object originally pointed to by this during the method's execution by including the myObject identifier in its signature and then binding that to the captureThisDuringExecution(MyClass) pointcut. See AlsoRecipe 4.1 shows some of the wildcard variations that can be used in a Signature; the execution(Signature) pointcut is shown in Recipe Recipe 4.4; how to capture parameters on a join point, in particular on a method call, is shown in Recipe 4.2; Recipe 11.1 discusses the this(Type | Identifier) pointcut; combining pointcut logic using a logical AND (&&) is shown in Recipe 12.2; the before( ) form of advice is shown in Recipe 13.3. |