Search code examples
javaaopaspectj

How can I weave aspect code into existing class files within JARs?


I am new to aspectj and I have one doubt whether we can inject the code before the function that exists in the jar file using aspectj.


Solution

  • Yes, you can weave aspect code into third-party class files or JARs. There are two ways to achieve that:

    • Binary weaving: Use the AspectJ compiler ajc in order to apply your aspects upon class files in an existing JAR. For that purpose, put the JAR on the compiler's inpath. After compilation you can re-package the newly woven class files into a new JAR which then you can deploy and use instead of the original one.
    • Load-time weaving (LTW): Start the JVM with the AspectJ weaving agent via command line option -javaagent:pathto/aspectjweaver.jar in order to achieve aspect weaving during classloading. This way you sacrifice some start-up time, but do not need to create a modified JAR file. Everything happens dynamically.

    And now please read some AspectJ documentation.