Search code examples
javacode-generationaspectjannotation-processing

AspectJ weaving: How to do a full code weave without static reference to the aspect?


a few weeks ago i was looking for a way to create some String constants for the fileds of a java class -> Generate constants for class attributes with maven?

I got it working. I create an aspect containing the constants and weave them into the class files. The problem is now, that my clients get an NoClassDefFound Exception when they try to use the weaved class. There are two reasons for that:

  1. I'm removing the aspect .class files from the client jar during the build process

  2. They do not have an aspectj lib in their classpath

Using a decompiler, i found out that the class got a static block like this:

static {
CarDTOAspect.ajc$interFieldInit$my.package.CarDTOAspect$my.package.CarDTO$VENDOR(); 
CarDTOAspect.ajc$interFieldInit$my.package.CarDTOAspect$my.package.CarDTO$NAME();
}

My question: Is there an option in the weave procedure, that creates real "public static final String"-Field in my class file, so that i can totally get rid of the aspects in my client jar?

Thanks in advance

martin


Solution

  • Unfortunately, no. This is not what AspectJ is designed to do. Intertype declarations must actually live in the Aspect (with a generated reference in the target type). This is because scoping rules may allow two fields of the same name to be added to a target type. Eg:

    class C { }
    aspect A1 { private int C.field = 9; }
    aspect A2 { private String C.field = "what???"; }
    

    This is completely legal. Neither field is accessible inside of C. They are only accessible inside of the aspect that declares them.

    If you are looking to do byte code manipulation, then i'd recommend something like ASM or Javassist.