---
description: Lombok annotations, with an emphasis on the lesser-known and advanced ones.
---

# Lombok

### 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 effectively `final` (cannot be reassigned).
* Type inference is handled at compile time

```java
val list = new ArrayList<String>();
// The type of `list` is inferred as `ArrayList<String>`
```

### Annotations-&#x20;

```
@Getter, @Setter, @NoArgsConstructor, @AllArgsConstructor, @Builder, @Log4j2,
@Slf4j
```

### @Value

* <mark style="color:orange;">Immutable class generator.</mark>
* Combines `@Getter`, `@ToString`, `@EqualsAndHashCode`, and makes all fields `private` and `final`.
* Automatically provides a constructor for all fields.

```java
@Value
public class ImmutableUser {
    String name;
    int age;
}
```

### @SneakyThrows

* Automatically handles checked exceptions, re-throwing them as unchecked exceptions.

```java
@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.

```java
@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`.

```java
@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.

```java
@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.

```java
@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:**

```java
@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.

```java
@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.

```java
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.&#x20;
* We can customize it using exclude or include attributes.

```java
@ToString(exclude = "password")
```

### **@EqualsAndHashCode**&#x20;

* Generates `equals()` and `hashCode()` methods.
*   Customize by excluding fields:

    ```java
    @EqualsAndHashCode(exclude = "id")
    ```

### @RequiredArgsConstructor&#x20;

* 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.







