Lombok
Lombok annotations, with an emphasis on the lesser-known and advanced ones.
Lombok Variables
val
Behaves like
final
for local variables. It infers the type based on the assigned value.Similar to
var
in Java 10+, but it works with earlier Java versions.Variables declared with
val
are effectivelyfinal
(cannot be reassigned).Type inference is handled at compile time
Annotations-
@Value
Immutable class generator.
Combines
@Getter
,@ToString
,@EqualsAndHashCode
, and makes all fieldsprivate
andfinal
.Automatically provides a constructor for all fields.
@SneakyThrows
Automatically handles checked exceptions, re-throwing them as unchecked exceptions.
@Cleanup
Ensures resources are automatically closed after use (e.g., streams or connections).
Equivalent to using a
try-with-resources
block.
@UtilityClass
Converts a class to a utility class by:
Marking it
final
.Adding a private constructor.
Making all fields/methods
static
.
@FieldDefaults
Configures default visibility and modifiers for fields in a class.
@Getter(lazy = true)
Generates a lazily initialized getter for a field. Useful for expensive operations.
@FieldNameConstants
Generates constants for field names, useful for reflection or query building.
The constants are generated as a nested static class.
Example:
@Accessors
Customizes the naming and chaining behaviour of getters and setters.
@With
It generates "with" methods for immutable objects.
It only works with fields that are
final
(commonly used with immutable classes).The generated method returns a new instance of the class with the specified field value changed.
@ToString
Generates a
toString()
method including all fields by default.Be cautious while using it as it will include subclasses as well, that could trigger n+1 queries.
We can customize it using exclude or include attributes.
@EqualsAndHashCode
Generates
equals()
andhashCode()
methods.Customize by excluding fields:
@RequiredArgsConstructor
Constructor for final or
@NonNull
fields.It will not include any other annotations applied to the filed. If want to include those annotations also like @value or @Qualifier then need to declare a parameterized constructor.
@Data
Combines
@Getter
,@Setter
,@ToString
,@EqualsAndHashCode
, and@RequiredArgsConstructor
.Suitable for simple POJOs.
Not customizable per individual feature, so avoid overuse.
Last updated