Aspect weaving at runtime Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Aspect weaving at runtime without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m looking for a Java solution that would allow me to use AOP to weave new code on top of already running code at runtime. The key is not to require the restart of the JVM. Also, I’d like to remove the woven at runtime, leaving the old code running the way it was before weaving.

I’m thinking AspectJ load time weaving + runtime class loading/unloading would do it. Has anyone tried it? Any recommendations?
Thank you.


A few things to consider:

  • True, you can do LTW during class loading, but not after a class has already been loaded.
  • There is no such concept as class unloading because for a class to be unloaded it needs to be garbage-collected and for that no references to the class must exist anymore. Even if the latter was the case, the JVM specification AFAIK declares it as optional whether or not and when unloading or GC should clear off an already loaded class. You could never rely on it.

Having said that, you either can try concepts such as OSGi or write your own class loader (or find one of many existing ones on the Internet) which loads each class or each JAR in a separate classloader instance. This can get arbitrarily complex, so maybe you want to consider this simple approach as long as it is within the technical bounds of your situation:

  • Compile your aspects into your code or use LTW, it does not really matter. Just make sure that the aspect code is woven before the classes are actually used. Compile time is obviously more than soon enough, load time is just barely soon enough, but fine.
  • Use if() pointcuts for all relevant advice and provide a means to dynamically change the value of the variable used by the pointcuts so as to be enable to dynamically switch advice on and off. The performance overhead will usually be minimal, don’t worry. Just give it a try before you say it is too expensive.

This solution satisfies your conditions that it can be (de)activated dynamically and that no JVM restart is necessary after the aspect code has been woven.

We are here to answer your question about Aspect weaving at runtime - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji