Lombok
Lombok annotations, with an emphasis on the lesser-known and advanced ones.
Lombok Variables
val
Behaves like
finalfor local variables. It infers the type based on the assigned value.Similar to
varin Java 10+, but it works with earlier Java versions.Variables declared with
valare effectivelyfinal(cannot be reassigned).Type inference is handled at compile time
val list = new ArrayList<String>();
// The type of `list` is inferred as `ArrayList<String>`Annotations-
@Getter, @Setter, @NoArgsConstructor, @AllArgsConstructor, @Builder, @Log4j2,
@Slf4j@Value
Immutable class generator.
Combines
@Getter,@ToString,@EqualsAndHashCode, and makes all fieldsprivateandfinal.Automatically provides a constructor for all fields.
@Value
public class ImmutableUser {
String name;
int age;
}@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-resourcesblock.
@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
@NonNullfields.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