问题
Some of my Java classes have static methods marked with a special annotation, @Assert, containing sanity checks.
I'd like to perform these checks before any code gets actually executed. The best would be to call these methods from <clinit>. How to get similar behavior using AspectJ, and without modifying initial code?
回答1:
AspectJ provides a staticinitialization(TypePattern) pointcut definition that will select existing static initializers and intercept them. Doesn't appear to be able to add static initializers to classes that don't have them, however.
回答2:
Just to add to John's answer; the staticInitialization pointcut doesn't require there to be any static blocks, in which case it acts as a simple class load join point.
That would be the time to call your methods annotated with @Assert.
来源:https://stackoverflow.com/questions/8053802/aspectj-add-static-initializer-to-class