Use custom setter in Lombok's builder

Use custom setter in Lombok's builder

Lombok's @Builder annotation allows you to generate a builder class for your Java classes, simplifying object creation. By default, Lombok generates setter methods in the builder for all fields in your class. If you want to use a custom setter for a specific field when using Lombok's @Builder, you can achieve it by creating a custom method in your class and annotating it with @Builder.ObtainVia. Here's how you can do it:

Assume you have a class called Person with a field age, and you want to use a custom setter for the age field in the builder.

import lombok.Builder; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.Accessors; @Builder @Getter @Setter @ToString public class Person { private String name; private int age; // Custom setter for age field @Accessors(chain = true) @Builder.ObtainVia public void setAge(int age) { if (age >= 0) { this.age = age; } else { throw new IllegalArgumentException("Age must be non-negative."); } } } 

In this example:

  1. We have a Person class with a name and age field.

  2. We use Lombok's @Builder annotation to generate a builder class for Person.

  3. We define a custom setter method for the age field, annotated with @Builder.ObtainVia. This custom setter checks if the provided age is non-negative and sets the field accordingly. We also use @Accessors(chain = true) to allow method chaining when using the setter.

Now you can use the custom setter when creating a Person object with the builder:

public class BuilderExample { public static void main(String[] args) { Person person = Person.builder() .name("Alice") .age(30) // Use custom setter .build(); System.out.println(person); } } 

By using this approach, you can define custom logic in the setter method while still benefiting from Lombok's builder pattern.


More Tags

linq-to-sql replace kendo-datepicker unhandled-exception distutils extending dialect url-pattern spam avcapturesession

More Java Questions

More Statistics Calculators

More Stoichiometry Calculators

More Biochemistry Calculators

More Gardening and crops Calculators