Immutable Java class using Lombok

 We can generate an Immutable class in Java using @Value annotation of Lombok.

What is Immutable in Java?

An object is considered immutable if its state cannot change after it is constructed. We can create immutable class in Java by following below give steps:

  1. Declare the class as final so it can not be extended.
  2. Make all fields private so that direct access is not allowed.
  3. Don’t provide setter methods for fields.
  4. Make all mutable fields final so that its value can be assigned only once.
  5. Initialize all the fields via a constructor during instantiation of the class.
Below class shows an example of an Immutable class using core Java

Immutable class using @Value annotation of Lombok

Lombok is a Java library that auto generates lots of boiler plate code for Java classes. Lombok works at compile time and manipulates Java byte code to add additional features. Lombok uses annotations to specify what boiler plate code will be generates.

Lombok provides @Value annotation to create an immutable class. As per Lombok documentation:
@Value is the immutable variant of @Data; all fields are made private and final by default, and setters are not generated. The class itself is also made final by default, because immutability is not something that can be forced onto a subclass. Like @Data, useful toString(), equals() and hashCode() methods are also generated, each field gets a getter method, and a constructor that covers every argument (except final fields that are initialized in the field declaration) is also generated.

Add Lombok to your project. If you use Maven as build tool then following Lombok  dependency should be added.

Now simply annotate your class with @Value annotation to obtain an Immutable class. 

0 comments:

Post a Comment