Browse DevX
Sign up for e-mail newsletters from DevX


AspectJ in Practice: Reap the Benefits of Modularity : Page 4

AspectJ, a general-purpose, aspect-oriented extension to the Java language, contains expansions and tools that enable Java developers to better manage the problems in large program systems and to reap the benefits of modularity. Get a crash course in this valuable new technology.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.

Olexiy Prokhorenko is a software and Web developer with more than six years development experience in complex, database-driven Web applications. .
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date