Search code examples
javaclassloaderaspectj

Are static initializers guaranteed to be called for AspectJ aspects?


This is my first question so please be gentle. :-) I know AspectJ can create pointcuts on static initializers of java classes. But the question is whether a static initializer in an aspect, as below, is guaranteed to be called exactly once:

@Aspect
public class MyAspect {
  private static Map configuration;
  static {
    // Some initialization stuff
    configuration = Config.getConfiguration();
  }
  ... use the "configuration" map in pointcuts and advices
}

In other words, is an aspect loaded like a java class is loaded? Is this done via a ClassLoader? I am guessing yes - and it seems to work - but I am looking for a guarantee along those lines.


Solution

  • AspectJ works using bytecode modification. This modification can happen wither at compile time ("compile-time weaving", or CTW), or at load-time ("Load-time weaving", or LTW).

    If you want to be sure, then I suggest you use the aspectj compiler to perform CTW on your example, and then pass the resulting class files through the javap tool (or something like it) to see what it has actually generated. That should give you the reassurance that it is (or isn't) doing what you think it does.