AspectJ is a programming language that enables you to write Aspect Oriented code for Java. The terms I’m going to explain in this article probably apply to every other Aspect Oriented language but I’m going to give examples in AspectJ code. Let’s start:
You describe with AspectJ where to weave in the crosscutting logic and what to weave in. To do this you need at first identifieable points called join points.
Join Point
“A join point is an identifiable point in the execution of a program”. A join point is quasi everything within your class. For example a call to a method, an assignment to an instance variable and so forth. These join points represent the places where the crosscutting logic can be woven in. Join points do reside in classes.
Example:
public class MyClass {
…
public void doSomething(int parameter) {
instanceVariable = parameter;
}
}
The join points in this class are the execution of the doSomething method as well as the assignment of the variable instanceVariable.
Aspect
The aspect is the main construct of your aspect code. You can compare it with a class although there are varieties.
Example:
public aspect MyAspect {
}
Pointcut
You somehow need to select a join point in your aspect. You do this with a pointcut.
Example:
execution(void MyClass.doSomething(int))
You now capture the execution of the doSomething() method in the class MyClass. But you also want to execute code when the execution takes place. Thus you need an advice.
Advice
“An Advice is the code to be executed at a join point that has been selected by a pointcut”. You have different opportunities when the execution shall take place: before, after or around the join point.
Example:
before() : execution(void MyClass.doSomething(int)) {
System.out.println(”The doSomething() method will be executed.”);
}
Example that sums everything up:
public class MyClass {
private int instanceVariable;
public void doSomething(int parameter) {
instanceVariable = parameter;
}
}
public aspect MyAspect {
before() : execution(void MyClass.doSomething(int)) {
System.out.println(”The doSomething() method will be executed.”);
}
}
If you now compile the aspect MyAspect the System.out.println() call will be woven into the code of the class MyClass. The result would decompiled probably look like the following:
public class MyClass {
private int instanceVariable;
public void doSomething(int parameter) {
System.out.println(”The doSomething() method will be executed.”);
instanceVariable = parameter;
}
}
Okay that are basics for now. The next article will go more in depth.
