Chapter 13. Defining Advice

Introduction

This chapter examines the different ways that advice can be specified in AspectJ. Pointcuts define which join points you are interested in and advice defines what to do when those join points are encountered.

An advice block contains straightforward Java code. Advice looks much like a Java method, except that it cannot be called directly from your application. It is the AspectJ runtime system that executes the advice according to the pointcut logic associated with that advice.

This chapter begins by examining how advice can interact with your application’s classes, including the mechanisms by which to access the triggering join point context. The different types of advice are then discussed before finally covering advice precedence and how the order in which advice is invoked can be controlled where more than one piece of advice is applied to the same join point.

13.1. Accessing Class Members

Problem

You want to access attributes and methods of a particular object from within your advice.

Solution

Pass the appropriate object to the advice as a parameter on your pointcut declaration.

Discussion

Example 13-1 shows how to access public and private members of a class whose object is available as the call join point is encountered.

Example 13-1. Passing an object to advice for access to its methods and attributes
public privileged aspect MemberAccessRecipe { /* Specifies calling advice whenever a method matching the following rules gets executed: Class Name: ...

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.