How to use aspectJ to add functionality temporarily to some java application? Something like creating the aspect, compiling with ajc, using java command with some extra switch to apply aspect?
The question, I believe is can you enable/disable the code weaved by Aspectj during runtime.
I don't know if there is a built in mechanism in AspectJ but I am sure that you can wrap the Code in the Aspect with a conditional statement. Then all you need to do is at runtime switch that code on or off
for example
// HelloWorld.java
public class HelloWorld {
public static void say(String message) {
System.out.println(message);
}
public static void sayToPerson(String message, String name) {
System.out.println(name + ", " + message);
}
}
// PoliteHelloWorld.java
public aspect PoliteHelloWorld {
pointcut callSayMessage() : call(public static void HelloWorld.say*(..));
before() : callSayMessage() {
if( is_aspectj_turned_on_this_run() ) {
System.out.println("Good day!");
}
}
after() : callSayMessage() {
if( is_aspectj_turned_on_this_run() ) {
System.out.println("Thank you!");
}
}
}
How you want to implement the "is_aspect_j_turned_on_this_run()
" is up to you (maybe set by command line arguments or user input?)
There is a better way, which is to right an aspect that handles the aspect you wish to disable at runtime. This new extra aspect will only be responsible for checking your "is_aspect_j_turned_on_this_run()
". For details of this cleaner method look here
I don't know if there is a better way to do this than these two methods (very well could be) but this at least allows you to turn it on and off at runtime as many times as you wish without recompiling.