Recipe 4.3. Capturing the Target of a Method CallProblemYou want to capture the object being called as a method is invoked. SolutionCreate a pointcut that specifies a single parameter of the same type as the target of the method call that you want to capture. Use the call(Signature) and target(Type | Identifier) pointcuts to capture the invocation of a method and then to bind the single identifier to the object that the method is being called upon. DiscussionExample 4-3 shows the call(Signature) pointcut being used to declare an interest in all methods that match the signature MyClass.foo(int,String). The captureCallTarget(MyClass) pointcut requires a MyClass object as specified by the myObject identifier. The myObject identifier is then bound to the object that is being called by the MyClass.foo(int,String) method by the target(Type | Identifier) pointcut. Example 4-3. Capturing the object upon which the MyClass.foo(..) method is invokedpublic aspect CaptureCallTargetRecipe { /* Specifies calling advice whenever a method matching the following rules gets called: Class Name: MyClass Method Name: foo Method Return Type: void Method Parameters: an int followed by a String */ pointcut captureCallTarget(MyClass myObject) : call(void MyClass.foo(int, String)) && target(myObject); // Advice declaration before(MyClass myObject) : captureCallTarget(myObject) { System.out.println( "------------------- Aspect Advice Logic --------------------"); System.out.println( "In the advice attached to the call point cut"); System.out.println("Captured target object for the method call: " + myObject); System.out.println( "------------------------------------------------------------"); } } The before( ) advice can access the single identifier declared on the captureCallTar-get(MyClass) pointcut by including the myObject identifier in its signature and then binding that identifier to the captureCallTarget(MyClass) pointcut. See AlsoThe call(Signature) pointcut is described in Recipe 4.1; Recipe 4.1 also shows some of the wildcard variations that can be used in a Signature; Recipe 11.2 discusses the target(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; the calling context that is available to advice is covered in Chapter 13. |