Member-only story
Beyond Lombok: Modern Java Code Generation Tools

As Java developer, you are likely familiar with Lombok, the popular Java library that helps reduce boilerpate code. The magic happens in compile time when Lombok generates setter, getters, constructors, etc. The Lombok despite its powerfull and popularity not only player in Java code generation space. In this article, we will explore two other modern Java generation tools: MapStruct and Java Poet. I will try to explain how it works under the hood
Lombok: Annotation — based code generation
Let’s briefly discuss how Lombok works. Lombok relies on annotations to generate code at compile time. The Lombok’s annotation processor kicks in during compilation and generates the corresponding Java bytecode.
The Lombok utilize Java’s annotation processing API to hook into compilation process. During compliation it scans your source files for annotations and modifies the abstract syntax tree (AST) of your code to include generated methods. This steps occurs before the javac converts the AST to bytecode, so from compiler’s perspective, it’s as if you wrote the boilerplate code yourself.
While Lombok is excellent tool for reduceing boilerplate code, it has some pitfalls. The Lombok’s primarily focused on generating code within a single class.
Here is an example of how Lombok annotations can be used:
@Getter
@Setter
@ToString
public class User {
private String name;
private int age;
@Builder
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
In code above we have a User
class with annotations @Getter, @Setter and @ToString.
These annotations instruct Lombok to generate the corresponding methods.
The @Builder
annotatition instructs Lombok to generate a builder patter for creating User objects.
User user = User.builder()
.name("John Doe")
.age(25)
.build();
MapStruct: Declarative Mapping between Java Beans
MapStruct helps developers with mapping between Java bean types. It is useful when you need to convert from one data transfer object to another or map…