Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java code transform at compile time

I would like to transform java source code at compile time just before passing the source code to the compiler. In other word I would like to create a preprocessor able to transform

"bla bla bla" 

into any other code such as:

new MyClass("bla", 3) 

My actual motivation is to do string encryption, as explained here

Some people suggest writing custom annotation processors but as far as I understand annotations:

  • they can be used to generate new class file, but not to transform existing code before being passed to compiler
  • they seem to work at package, class or method level, but not method body/implementation.

Some people suggest using frameworks like Spoon or ObjectsWeb ASM, but these frameworks seem complicated to learn and deploy on an existing code base.

I thrive to find a simple example of java code preprocessing for both approaches.

Does anybody see any smart way of doing code transform, without completely changing an existing large code base with multiple ivy module? Annotations seem to be the best way, but I don't understand how to do that.

like image 723
Martin Avatar asked Sep 08 '25 18:09

Martin


1 Answers

I think you could try the same technique used in Project Lombok

It's approximately explained by the authors in this interview:

What's going on under the hood? I.e., how does an annotation result in the boilerplate ending up in the bytecode?

Reinier: The annotation processor API only lets you create new files, it does not let you modify the file that has the annotation inside of it. Which is what Lombok does, so Lombok does not use the annotation processor API.

Instead, Lombok uses the annotation processor API only as a mechanism to inject itself into the compilation process. All annotation processors are initialized early in the compilation process, and Lombok modifies javac when it is initialized as an annotation processor. We change only one thing: The AST (the raw source code, parsed into a tree form) is first handed off to Lombok, which generates whatever needs to be generated, before javac continues.

and in How does lombok work?

It's also possible to extend Project Lombok to your needs

  • Custom AST transformations with Project Lombok
  • Project Lombok: Creating Custom Transformations
like image 112
fglez Avatar answered Sep 10 '25 08:09

fglez