16.3 Injecting Methods Using AST Transformations
We saw how to inject code into existing methods. We can also inject new methods and fields into classes by using AST transformations. This gives us the full power of aspect-oriented programming (AOP) at compile time without the need for any third-party libraries.
In the Execute Around Method pattern from Section 4.5, Using Closures for Resource Cleanup, a static method helped create and clean up instances. This method yielded the instance for arbitrary use in between these two operations. Let’s implement that pattern using AST transformations. Rather than asking the programmer to implement the
use
method by hand, we can create it; the programmer just has to ask—nicely.
The AST transformations ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access