Chapter 16. Enhancing Classes and the Compiler
Introduction
This chapter shows how aspects in AspectJ can be used statically to introduce behavior and interfaces to existing classes using static cross-cutting techniques. Using these techniques, classes can be extended to implement interfaces, extend from new parent classes, introduce new methods and attributes, soften exceptions that are raised, and inherit from multiple base classes.
Static cross-cutting is powerful and must be used with care. Problems that were deliberately avoided by language constraints, such as multiple inheritance complications, are possible and must be considered before they are used. There are two schools of thought on this. Some people argue the developer should decide if they want to use the more complex techniques and, therefore, accept the potential problems. Others, such as the designers of Java, attempt to constrain these decisions as much as possible using the language.
Ultimately, the individual’s opinions or the organization’s style determines whether static cross-cutting techniques are acceptable. However, it is useful to know that these techniques exist within the aspect developers toolbox.
16.1. Extending an Existing Class
Problem
You want to extend an existing class.
Solution
Declare the new methods and attributes to be added to the existing class within the aspect.
Discussion
Example 16-1 shows how an attribute and a method can
be introduced to the MyClass
class.
Get AspectJ Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.