Recipe 7.3. Capturing When an Object Is InitializedProblemYou want to capture when an object is initialized, invoked by a call to a constructor that matches a specific signature. SolutionUse the initialization(Signature) pointcut. The syntax of the initialization(Sig-nature) pointcut is: pointcut <pointcut name>(<any values to be picked up>) : initialization(<optional modifier> <class>.new(<parameter types>)); DiscussionThe initialization(Signature) pointcut has five key characteristics:
Example 7-3 shows the initialization(Signature) capturing the initialization of objects of MyClass when the constructor has the signature MyClass.new(int,*). Example 7-3. Using the initialization(Signature) pointcut to capture join points when a constructor is executingpublic aspect InitializationRecipe { /* Specifies calling advice when any object initializes using a constructor that meets the following signature rules: Class Name: MyClass Method Name: new (This is a keyword indicating the constructor call) Method Parameters: int and any others */ pointcut myClassObjectInitializationWithIntAndOthersPointcut( ) : initialization(MyClass.new (int, *)); // Advice declaration before( ) : myClassObjectInitializationWithIntAndOthersPointcut( ) { System.out.println( "-------------- Aspect Advice Logic ---------------"); System.out.println( "In the advice picked by " + "myClassObjectInitializationWithIntAndOthersPointcut( )"); System.out.println( "The current type of object under construction is: "); System.out.println(thisJoinPoint.getThis( ).getClass( )); System.out.println( "Signature: " + thisJoinPoint.getStaticPart( ).getSignature( )); System.out.println( "Source Line: " + thisJoinPoint.getStaticPart( ).getSourceLocation( )); System.out.println( "--------------------------------------------------"); } } Figure 7-3 shows how the initialization(Signature) pointcut is applied to pick join points on constructors. Figure 7-3. How the initialization(Signature) pointcut is appliedThe biggest advantage to using the initialization(Signature) pointcut over the execution(Signature) pointcut is in the compile-time checking that occurs to ensure that the signature is actually specifying a constructor. See AlsoRecipe 4.1 shows some of the wildcard variations that can be used in a Signature; Recipe 7.2 shows the execution(Signature) pointcut for a comparison of its similarities to this recipe; Chapter 13 describes the different types of advice available in AspectJ. |