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
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 fieldsprivate
andfinal
.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.
@SneakyThrows
public void readFile() {
Files.readAllLines(Paths.get("file.txt")); // No need for try-catch or throws declaration
}
@Cleanup
Ensures resources are automatically closed after use (e.g., streams or connections).
Equivalent to using a
try-with-resources
block.
@Cleanup
InputStream inputStream = new FileInputStream("file.txt");
@UtilityClass
Converts a class to a utility class by:
Marking it
final
.Adding a private constructor.
Making all fields/methods
static
.
@UtilityClass
public class MathUtils {
public int add(int a, int b) {
return a + b;
}
}
@FieldDefaults
Configures default visibility and modifiers for fields in a class.
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class User {
String name;
int age;
}
@Getter(lazy = true)
Generates a lazily initialized getter for a field. Useful for expensive operations.
@Getter(lazy = true)
private final String expensiveValue = computeExpensiveValue();
private String computeExpensiveValue() {
return "Computed Value";
}
@FieldNameConstants
Generates constants for field names, useful for reflection or query building.
The constants are generated as a nested static class.
Example:
@FieldNameConstants
public class User {
private String name;
private int age;
}
// Usage:
String fieldName = User.Fields.name; // "name"
@Accessors
Customizes the naming and chaining behaviour of getters and setters.
@Accessors(chain = true)
public class User {
private String name;
}
// Usage:
User user = new User().setName("Alice").setAge(25);
@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.
import lombok.With;
public class User {
@With
private final String name;
@With
private final int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
// Usage:
User user1 = new User("Alice", 25);
User user2 = user1.withAge(30); // Creates a new User instance with the modified age
// user1 is still ("Alice", 25)
// user2 is ("Alice", 30)
@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.
@ToString(exclude = "password")
@EqualsAndHashCode
Generates
equals()
andhashCode()
methods.Customize by excluding fields:
@EqualsAndHashCode(exclude = "id")
@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