In all my previous posts under Lombok, I used Pojo classes as an example.
All these Pojo classes are mutable since they have setter and getter method.
In this post, I will show with example how to create an immutable class.
To create an immutable class, we annotate a Pojo class with “@Value” annotation and we declared the fields as private final.
The “@Value” annotation is applied at the class level as shown below
Person class
package package23;
import lombok.Value;
@Value
public class Person {
private final String firstName;
private final String middleName;
private final String lastName;
private final float salary;
}
In the above Pojo class “Person”.
It is annotated with “@Value” annotation.
All the fields are private and final.
In addition to making the Pojo class as immutable, it also generates “toString”, “hashCode”, and “equals” methods.
It also generates a constructor with all fields.
Below is the main class that shows the usage.
Main class
package package23;
public class Example23 {
public static void main(String[] args) {
Person person = new Person("Ellis", "M", "Robertson", 1000.50f);
System.out.println(person);
}
}