Member-only story

Beyond Lombok: Modern Java Code Generation Tools

Egor Voronianskii
4 min readSep 5, 2024

Image generated by Midjourney

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Egor Voronianskii
Egor Voronianskii

Written by Egor Voronianskii

I am a Software Engineer, JVM enthusiast, cat - lover, part-time surfer.

Responses (4)

Write a response

Lombok is redundant for modern Java.

17

JavaPoet is dead. The repository is archived. Try https://github.com/forge/roaster

11

lol javapoet to reduce boilerplate, looking at the example i beg to differ

6