DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The First Annual Recap From JPA Buddy
  • How to Use Java to Build Single Sign-on
  • Pros and Cons for Using GraalVM Native-Images
  • A Systematic Approach for Java Software Upgrades

Trending

  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • The Role of Functional Programming in Modern Software Development
  • SQL Server Index Optimization Strategies: Best Practices with Ola Hallengren’s Scripts
  • Rust and WebAssembly: Unlocking High-Performance Web Apps
  1. DZone
  2. Coding
  3. Java
  4. Reduce Boilerplate Code in your Java applications with Project Lombok

Reduce Boilerplate Code in your Java applications with Project Lombok

By 
Michael Scharhag user avatar
Michael Scharhag
·
Sep. 22, 14 · Interview
Likes (1)
Comment
Save
Tweet
Share
24.9K Views

Join the DZone community and get the full member experience.

Join For Free

One of the most frequently voiced criticisms of the Java programming language is the amount of Boilerplate Code it requires. This is especially true for simple classes that should do nothing more than store a few values. You need getters and setters for these values, maybe you also need a constructor, overridingequals() and hashcode() is often required and maybe you want a more useful toString()implementation. In the end you might have 100 lines of code that could be rewritten with 10 lines of Scala or Groovy code. Java IDEs like Eclipse or IntelliJ try to reduce this problem by providing various types of code generation functionality. However, even if you do not have to write the code yourself, you always see it (and get distracted by it) if you open such a file in your IDE.

Project Lombok (don't be frightened by the ugly web page) is a small Java library that can help reducing the amount of Boilerplate Code in Java Applications. Project Lombok provides a set of annotations that are processed at development time to inject code into your Java application. The injected code is immediately available in your development environment.
Lets have a look at the following Eclipse Screenshot:

The defined class is annotated with Lombok's @Data annotation and does not contain any more than three private fields. @Data automatically injects getters, setters (for non final fields), equals(), hashCode(),toString() and a constructor for initializing the final dateOfBirth field. As you can see the generated methods are directly available in Eclipse and shown in the Outline view.

Setup
To set up Lombok for your application you have to put lombok.jar to your classpath. If you are using Maven you just have to add to following dependency to your pom.xml:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.14.8</version>
    <scope>provided</scope>
</dependency>

You also need to set up Lombok in the IDE you are using:

  • NetBeans users just have to enable the Enable Annotation Processing in Editor option in their project properties (see: NetBeans instructions).
  • Eclipse users can install Lombok by double clicking lombok.jar and following a quick installation wizard.
  • For IntelliJ a Lombok Plugin is available.


Getting started
The @Data annotation shown in the introduction is actually a shortcut for various other Lombok annotations. Sometimes @Data does too much. In this case, you can fall back to more specific Lombok annotations that give you more flexibility.

Generating only getters and setters can be achieved with @Getter and @Setter:

@Getter
@Setter
public class Person {
    private final LocalDate birthday;
    private String firstName;
    private String lastName;
    public Person(LocalDate birthday) {
        this.birthday = birthday;
    }
}

Note that getter methods for boolean fields are prefixed with is instead of get (e.g. isFoo() instead ofgetFoo()). If you only want to generate getters and setters for specific fields you can annotate these fields instead of the class.

Generating equals(), hashCode() and toString():

@EqualsAndHashCode
@ToString
public class Person {
    ...
}

@EqualsAndHashCode and @ToString also have various properties that can be used to customize their behaviour:

@EqualsAndHashCode(exclude = {"firstName"})
@ToString(callSuper = true, of = {"firstName", "lastName"})
public class Person {
    ...
}

Here the field firstName will not be considered by equals() and hashCode().
toString() will call super.toString() first and only consider firstName and lastName.

For constructor generation multiple annotations are available:

  • @NoArgsConstructor generates a constructor that takes no arguments (default constructor).
  • @RequiredArgsConstructor generates a constructor with one parameter for all non-initialized final fields.
  • @AllArgsConstructor generates a constructor with one parameter for all fields in the class.


The @Data annotation is actually an often used shortcut for @ToString, @EqualsAndHashCode, @Getter,@Setter and @RequiredArgsConstructor.

If you prefer immutable classes you can use @Value instead of @Data:

@Value
public class Person {
    LocalDate birthday;
    String firstName;
    String lastName;
}

@Value is a shortcut for @ToString, @EqualsAndHashCode, @AllArgsConstructor,@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) and @Getter.

So, with @Value you get toString(), equals(), hashCode(), getters and a constructor with one parameter for each field. It also makes all fields private and final by default, so you do not have to addprivate or final modifiers. 


Looking into Lombok's experimental features
Besides the well supported annotations shown so far, Lombok has a couple of experimental features that can be found on the Experimental Features page.

One of these features I like in particular is the @Builder annotation, which provides an implementation of the Builder Pattern.

@Builder
public class Person {
    private final LocalDate birthday;
    private String firstName;
    private String lastName;
}

@Builder generates a static builder() method that returns a builder instance. This builder instance can be used to build an object of the class annotated with @Builder (here Person):

Person p = Person.builder()
    .birthday(LocalDate.of(1980, 10, 5))
    .firstName("John")
    .lastName("Smith")
    .build();


By the way, if you wonder what this LocalDate class is, you should have a look at my blog post about the Java 8 date and time API ;-)

Conclusion
Project Lombok injects generated methods, like getters and setters, based on annotations. It provides an easy way to significantly reduce the amount of Boilerplate code in Java applications. 
Be aware that there is a downside: According to reddit comments (including a comment of the project author), Lombok has to rely on various hacks to get the job done. So, there is a chance that future JDK or IDE releases will break the functionality of project Lombok. On the other hand, these comments where made 5 years ago and Project Lombok is still actively maintained.

You can find the source of Project Lombok on GitHub. 

Java (programming language) Boilerplate code code style application

Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The First Annual Recap From JPA Buddy
  • How to Use Java to Build Single Sign-on
  • Pros and Cons for Using GraalVM Native-Images
  • A Systematic Approach for Java Software Upgrades

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!