Java Lombok | Value Objects - @Value

@Value

When the @Value annotation is declared on a class, all of the following annotations are applied.

  • @Getter
  • @ToString
  • @EqualsAndHashCode
  • @AllArgsConstructor

In addition, the class and each field become final, and each field automatically receives the private access modifier. This makes it suitable as a DDD value object.

package com.devkuma.tutorial.lombok;

import lombok.Value;

@Value
public class ValueTutorial {

    String string;
    int number;
}

Because of @Value, the code above is transformed as follows.

package com.devkuma.tutorial.lombok;

public final class ValueTutorial {
    private final String string;
    private final int number;

    public ValueTutorial(String string, int number) {
        this.string = string;
        this.number = number;
    }

    public String getString() {
        return this.string;
    }

    public int getNumber() {
        return this.number;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof ValueTutorial)) {
            return false;
        } else {
            ValueTutorial other = (ValueTutorial)o;
            if (this.getNumber() != other.getNumber()) {
                return false;
            } else {
                Object this$string = this.getString();
                Object other$string = other.getString();
                if (this$string == null) {
                    if (other$string != null) {
                        return false;
                    }
                } else if (!this$string.equals(other$string)) {
                    return false;
                }

                return true;
            }
        }
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        result = result * 59 + this.getNumber();
        Object $string = this.getString();
        result = result * 59 + ($string == null ? 43 : $string.hashCode());
        return result;
    }

    public String toString() {
        String var10000 = this.getString();
        return "ValueTutorial(string=" + var10000 + ", number=" + this.getNumber() + ")";
    }
}