Thursday, February 16, 2023

Lombok Sample @Builder along with Generated Code

@Builder is an annotation provided by Lombok that can help reduce boilerplate code for creating objects with a builder pattern. The builder pattern is a design pattern that separates the construction of an object from its representation. This allows for more readable and maintainable code, as well as providing more flexibility in object creation.

With @Builder, Lombok generates code that allows you to create instances of a class using a fluent API. The generated code includes a builder class that has methods for setting the values of the class's fields, and a build() method that creates and returns an instance of the class. 


Usage: 

Movie movie = Movie.builder()
.Name("RRR")
.Year(2022)
.build();


Example:

import lombok.Builder;

@Builder
public class PersonBuilder {
        String Name;
        int Age;
}

Generated :

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

public class PersonBuilder {
String Name;
int Age;

PersonBuilder(final String Name, final int Age) {
this.Name = Name;
this.Age = Age;
}

public static PersonBuilder.PersonBuilderBuilder builder() {
return new PersonBuilder.PersonBuilderBuilder();
}

public static class PersonBuilderBuilder {
private String Name;
private int Age;

PersonBuilderBuilder() {
}

public PersonBuilder.PersonBuilderBuilder Name(final String Name) {
this.Name = Name;
return this;
}

public PersonBuilder.PersonBuilderBuilder Age(final int Age) {
this.Age = Age;
return this;
}

public PersonBuilder build() {
return new PersonBuilder(this.Name, this.Age);
}

public String toString() {
return "PersonBuilder.PersonBuilderBuilder(Name=" + this.Name + ", Age=" + this.Age + ")";
}
}
}

No comments:

Post a Comment