Lombok

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

External

Overview

Lombok is a Java annotation library that helps reduce boilerplate code.

Gradle Dependency

dependencies {
    implementation('org.projectlombok:lombok')
}

Annotations

@Slf4j

The annotation generates a SLF4J Logger in the class. It has the same effect as if you were to explicitly add the following lines within the class:

private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MyClass.class);

@Data

https://projectlombok.org/features/Data

Generates:

  • Getters for all fields
  • Setters for all non-final fields
  • A constructor with corresponding arguments for all fields
  • A useful toString() method
  • hashCode() and equals() implementations that check all non-transient fields

Equivalent to @Getter @Setter, @RequiredArgsConstructor @ToString @EqualsAndHashCode

@Getter

@Setter

@RequiredArgsConstructor

Generates a constructor with required arguments. Required arguments are final fields and fields with constraints such as @NonNull.

@NoArgsConstructor

@NoArgsConstructor(access=AccessLevel.PRIVATE, force=true)

Generates a no-argument constructor and make it private. This is usually applied to JPA @Entity classes. If the class has final properties that must be set, use "force=true", which results in the Lombok-generated constructor setting them to null. Note that when you use @NoArgsConstructor, an argument constructor, even if possible, will not get added, so if you need it, you will need to explicitly use @RequiredArgsConstructor.

@ToString

@EqualsAndHashCode

@NonNull

Troubleshooting

lombok.javac.apt.LombokProcessor could not be initialized. Lombok will not run during this compilation

When using:

dependencies {
    implementation('org.projectlombok:lombok')
}

we get:

warning: lombok.javac.apt.LombokProcessor could not be initialized. Lombok will not run during this compilation: 
java.lang.ClassCastException: org.gradle.api.internal.tasks.compile.processing.IncrementalFiler cannot be cast to com.sun.tools.javac.processing.JavacFiler

Fixed by explicitly specifying the Lombok version:

dependencies {
    implementation('org.projectlombok:lombok:1.18.2')
}