Compile AspectJ
Compilation is easy, too. Just execute the following:
ajc TestMe.aj TestClass.java
java TestClass
(Note: You can list as many .java files as you need after TestClass.java; all of them will use the aspects created in TestMe.aj)
The output will be the following:
-- TestClass.method1 start --
Hello World!
-- TestClass.method1 stop --
-- TestClass.method2 start --
Really Hello!
-- TestClass.method2 stop --
-- TestClass.say(I can talk!) start --
I can talk!
-- TestClass.say(I can talk!) stop --
Now do you see how useful AspectJ can be? Even this simple example shows the power of this technology. You didn't change a single line of your main class code, but you already have a perfect solution for logging or testing!
Another AspectJ Benefit
Another interesting functionality of aspect is very useful when you need localization. To see it, just comment lines 7-15 (otherwise it creates a circular dependency at method-call) and add the following code after them:
void around(String a): methodCallArg(a) {
proceed("it is not '" + a + "' anymore!");
}
Compile and run it the same way you did before. Look at the output. If you completed everything properly, you'll see that the say() method (which previously received the String "I can talk!") receives and outputs the next String: "it is not I can talk! anymore!" A real argument passed to the previously mentioned code, and only after being changed, did it pass directly to the say() method. This could serve as an interesting scheme with localization. For example, you can check some constants about which language you are using once, and then provide output in that exact language.