I trying to learn aspectj for a project. I wish to run the java files from the terminal using ajc and java but I am unable to do so.
I have 2 files in my directory HelloWorld.java and HWTracer.aj
Contents of Helloworld.java
public class HelloWorld {
public static void main(String[] args) {
printMsg("Hello, World!!");
}
public static void printMsg(String msg) {
System.out.println("\n");
System.out.println(" " + msg);
System.out.println("\n");
}
}
Contents of HWTracer.aj
public aspect HWTracer {
// pointcuts
pointcut theMainMethod() : execution(public static void main(String[]));
pointcut theCall() : call (* HelloWorld.printMsg(*));
// advice
before(): theMainMethod() {
System.out.println("Before the Main");
}
// note this is after main is done, after the entire program finishes
after(): theMainMethod() {
System.out.println("After the Main");
}
before(): theCall() {
System.out.println("-- before the call --");
}
after(): theCall() {
System.out.println("-- after the call --");
}
}
Here is the command I use to compile the code
ajc .\HelloWorld.java .\HWTracer.aj -cp C:\aspectj1.9\lib\aspectjrt.jar;C:\aspectj1.9\lib\aspectjtools.jar;C:\aspectj1.9\lib\aspectjweaver.jar
I run the compiled file using the following command:
java -cp C:\aspectj1.9\lib\aspectjrt.jar HelloWorld HWTracer
And I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/aspectj/lang/NoAspectBoundException
at HelloWorld.main(HelloWorld.java:5)
Please note that I am by no means a java expert.
On the compilation classpath, aspectjrt
should be enough, just like on the runtime one.
On the runtime classpath, you need to add the directory your compiled classfiles reside in, in your case obviously just the current directory "."
:
xxx> ajc -cp "lib\aspectjrt.jar" HelloWorld.java HWTracer.aj
xxx> java -cp ".;lib\aspectjrt.jar" HelloWorld
Before the Main
-- before the call --
Hello, World!!
-- after the call --
After the Main
Also note that when running the main class, there is no need to mention the aspect class separately. Java would interpret it as a command line parameter to the main class.
Please do learn some Java basics first, before you try to understand a complex tool like AspectJ. If you do not even know how to correctly run a Java program from the command line, maybe the time is not right yet to take the second step. Buildings without solid foundations tend to be shaky.