O'Reilly logo

AspectJ Cookbook by Russ Miles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.2. Overriding the Class Instantiated on a Call to a Constructor

Problem

You want to be able to control the actual classes that are instantiated on a constructor call.

Solution

Use the Cuckoo’s Egg aspect-oriented design pattern to create an aspect that modularizes the override of a constructor call to be able to vary the implementation returned at runtime. Use the call(Signature) pointcut to capture calls to a classes constructor and then use around( ) advice to return a different object.

Discussion

It can be useful to be able to migrate to different implementations of an interface or specialization of a base class without affecting the code that uses that interface or base class. Traditionally, deciding the class selection is performed at object construction time, as shown in Example 20-4.

Example 20-4. Hardcoding the selection of the MyClass implementation of MyInterface

public static void traditionalObjectOrientedImplementationSelection( )
{
   MyInterface myObject = new MyClass( ); // Specifies the MyClass  
                                         // implementation of the 
                                         // MyInterface interface
   
   System.out.println(myObject);
   myObject.foo( ); // Calls the MyClass implementation of the foo( ) method
}

This code produces the following output:

com.oreilly.aspectjcookbook.MyClass@cf8583
foo( ) called on MyClass

To change the implementation of MyInterface, the code would need to be changed to:

public static void traditionalObjectOrientedImplementationSelection( )
{
   MyInterface myObject = new AnotherClass( ); // Specifies the // AnotherClass ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required