It became interesting to me, but with the help of what can I generate code in methods, describing what to generate with annotations?


For example, there is the Lombok library, which generates code, depending on annotations. There is the @NonNull annotation, which is applied like this:

 void method(@NonNull Object arg) {} 

And it generates a check, something like:

 if (arg == null) throw new NullPointerException(); 

But, having rummaged in the source code of the library, I realized that I did not understand anything.


Actually the question is: how is it possible to generate code by taking any fields of a class / method at the compilation stage?

  • one
    Annotation processors are provided for this, which can be specified at compile time and are invoked by the compiler as soon as it sees the annotation corresponding to the processor. Well, the processor can probably something there nenerirovat. I am no longer familiar with this matter. Google by java code generation annotation processor compile time - Sergey
  • one
    And processors are connected very simply. Just like any jar-nickname, it is simply listed in the classpath. Inside META-INF there is a special file by which the compiler understands that this is not some kind of library, but an annotation processor. - Sergey

1 answer 1

Lombok based on annotation processing . To generate the code, use cglib . But jsr 269 itself does not imply a change to the bytecode of the classes being compiled. It provides a mechanism only for creating new classes, analyzing existing ones, etc. Therefore, lombok relies on the internal compiler classes, the compatibility of which between versions is not guaranteed, in part there is some kind of confusing code.