DEV Community

Cover image for Useful: Lombok Annotations
Yassine Sellami
Yassine Sellami

Posted on • Updated on

Useful: Lombok Annotations

Summary

  • Configuration
  • @ToString
  • @Tolerate
  • @StandardException

Configuration

-- Gradle: build.gradle

compileOnly 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'
Enter fullscreen mode Exit fullscreen mode

-- Maven: pom.xml

  <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
  </dependency>

<plugins>
  <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-compiler-plugin</artifactId>
     <version>3.8.0</version>
     <configuration>
         <source>11</source> <!-- depending on your project -->
         <target>11</target>
         <annotationProcessorPaths>
             <path>
                 <groupId>org.projectlombok</groupId>
                 <artifactId>lombok</artifactId>
                 <version>${lombok.version}</version>
             </path>
         </annotationProcessorPaths>
     </configuration>
   </plugin>
</plugins>
Enter fullscreen mode Exit fullscreen mode

@ToString

Generate an implementation of the toString() method.

@ToString(doNotUseGetters = true)
public class Account {
    private String id;
    private String name;
    @ToString.Exclude // Exclusion Field 
    private String adress;

    // ignored getter
    public String getId() {
        return "this is the id:" + id;
    }
}
@ToString(onlyExplicitlyIncluded = true)
public class Account {
    @ToString.Include(name = "accountId") // Modifying Field Names
    private String id;
    @ToString.Include(rank = 1) // Ordering Output
    private String name;
    private String adress;

    @ToString.Include // Method Output
    String description() {
        return "Account description";
    }
} => Account(name=An account, accountId=12345, description=Account description)


Enter fullscreen mode Exit fullscreen mode

@Tolerate

Skip, jump, and forget! Make lombok disregard an existing method or constructor.

public class TolerateExample {
    @Setter
    private Date date;

    @Tolerate
    public void setDate(String date) {
        this.date = Date.valueOf(date);
    }
}

Enter fullscreen mode Exit fullscreen mode

@StandardException

Put this annotation on your own exception types.will generate 4 constructors:

  • MyException(): representing no message, and no cause.
  • MyException(String message): the provided message, and no cause.
  • MyException(Throwable cause): which will copy the message from the cause, if there is one, and uses the provided cause.
  • MyException(String message, Throwable cause): A full constructor.

Top comments (0)