Recipe 7.2. Capturing a Constructor When It Is ExecutingProblemYou want to capture a constructor that matches a specific signature when it is executing. SolutionUse the execution(Signature) pointcut with the additional new keyword as part of the signature. The syntax of the execution(Signature) pointcut when using in relation to constructors is: pointcut <pointcut name>(<any values to be picked up>) : execution(<optional modifier> <class>.new(<parameter types>)); DiscussionThe execution(Signature) pointcut has three key characteristics when it is used to capture the execution of a constructor:
Example 7-2 shows the execution(Signature) capturing the execution of the MyClass constructor that takes an int and a String as parameters. Example 7-2. Using the execution(Signature) pointcut to capture join points within a specific constructorpublic aspect ExecutionNewRecipe { /* Specifies calling advice when any constructor executes that meets the following signature rules: Class Name: MyClass Method Name: new (This is a keyword indicating the constructor call) Method Parameters: int, String */ pointcut myClassConstructorWithIntAndStringPointcut( ) : execution(MyClass.new (int, String)); // Advice declaration before( ) : myClassConstructorWithIntAndStringPointcut( ) { System.out.println( "---------------- Aspect Advice Logic -----------------"); System.out.println( "In the advice picked by " + "myClassConstructorWithIntAndOthersPointcut( )"); System.out.println( "The current type of object under construction is: "); System.out.println(thisJoinPoint.getThis( ).getClass( )); System.out.println( "Signature: " + thisJoinPoint.getSignature( )); System.out.println( "Source Line: " + thisJoinPoint.getSourceLocation( )); System.out.println( "------------------------------------------------------"); } } Figure 7-2 shows how the execution(Signature) pointcut is applied to constructors. Figure 7-2. How the execution(Signature) pointcut is applied to constructorsSee AlsoRecipe 4.1 shows some of the wildcard variations that can be used in a Signature; describes how the call(Signature) pointcut is applied to constructors and is similar to this recipe's pointcut, with the exception that the call(Signature) pointcut has the power to override the object that is being constructed; Recipes Recipe 4.1 and Recipe 4.4 respectively show how to define the call(Signature) and execution(Signature) pointcuts to capture join points from regular methods; Chapter 13 describes the different types of advice available in AspectJ. |