Project Lombok: Put an End to Java Verbosity

n my never-ending search for interesting new ideas in the IT world, every now and then I come across something truly innovative and brilliant. Such was the case when I first stumbled upon the initial announcement of Project Lombok. In the two months since then, Project Lombok has become an indispensable part of my Java tool chain and I can’t imagine coding without it.

What Is Project Lombok?

Project Lombok is really two things: a compile-time code generator and a development-time code generator. It’s the latter that makes it so brilliant.

Basically, Lombok integrates directly into the Eclipse compilation cycle (by manipulating the abstract syntax tree of your code as you type) and generates code immediately based on annotations. The generated code is visible to all other classes instantly.

What type of code can Lombok generate from annotations? Most importantly, it generates the basic boilerplate stuff that makes Java classes look so verbose, namely:

  • getters and setters for fields
  • toString() representation of your POJOs
  • hashCode() and equals()

At the same time, Lombok provides automatic resource management. For example, it always closes your streams safely, without the need for try/catch/finally statements.

Figure 1. The Lombok Installation Wizard: Upon running the lombok.jar file, a simple wizard will pop up.

Lombok Installation and Maven Support

Lombok is provided as an executable JAR file (lombok.jar), and the development-time support currently works only in Eclipse. Upon running the JAR file, a simple wizard will pop up and ask you to specify where your Eclipse executable is located (see Figure 1).

Just point to your Eclipse executable and press “Install/Update.” You will need to do this for every new version of Lombok.

To include Maven support, just add the Project Lombok repository and dependencies to your pom.xml, as per the instructions on the project web site. After that, Lombok will work with Maven’s compilation lifecycle out of the box.

Project Lombok in Action

To fully grasp how Lombok decimates the number of lines in a typical Java POJO, consider the following typical Person entity:

public class Person  {   private Long personId;      private String salutation;   private String firstName;   private String middleName;   private String lastName;      private String phoneNumber;   private String email;   private String addressLine1;   private String addressLine2;   private String city;   private String state;   private String country;      private Calendar birthDate;}

In order to make this class a proper Java POJO, you have to code the getters, setters, toString(), equals(), and hashCode() for it. If you used Eclipse’s automatic code generation features, the Person POJO would mushroom to more than 240 lines of code, most of which is just plumbing (see Listing 1).

Here’s what the same POJO would look like after being “Lombok-omized”:

@Datapublic class Person  {   private Long personId;      private String salutation;   private String firstName;   private String middleName;   private String lastName;      private String phoneNumber;   private String email;   private String addressLine1;   private String addressLine2;   private String city;   private String state;   private String country;      private Calendar birthDate;   }

That’s it! When Lombok is installed into your Eclipse runtime, a simple @Data annotation makes all the standard plumbing code magically appear. This makes defining JPA/Hibernate entities incredibly easy and fast.

But wait, there’s more! All the getters and setters appear in the outline, as if the code were actually there (see Figure 2). What’s more, all the generated methods are available as if they were actually there. They show up in code completion (see Figure 3).


Figure 2. Auto-Generated Getters, Setters, equals(), hashCode() and toString(): All the getters and setters appear in the outline, as if the code were actually there.
 
Figure 3. Auto-Generated Methods Visible via Code Completion: All the generated methods are available as if they were actually there. They show up in code completion.

If you need more fine-grained control, Project Lombok offers @Getter, @Setter, @ToString, and @EqualsAndHashCode annotations as well. The previously mentioned @Data annotation combines them all into one. In our production code, @Data is the annotation I use 99% of the time.

Additional Lombok Features

Besides the core features you just saw, Lombok comes with a few extras:

  • The @Cleanup annotation provides automatic resource management. For example, in the following snippet, @Cleanup ensures that the close() method will be executed before the method exits:
    @Cleanup InputStream in = new FileInputStream(args[0]);@Cleanup OutputStream out = new FileOutputStream(args[1]);

    This feature offers automatic resource management in Java 6 today; you don’t have to wait for Java 7.

  • The @Synchronized annotation is an alternative to the synchronized keyword, but with better implementation:
    @Synchronizedpublic static void hello() {   System.out.println("world");}
  • The @SneakyThrows annotation disables Java’s checked exceptions:
    @SneakyThrowspublic void run() {   throw new Throwable();}

    Whether or not you choose to employ this feature (I have mixed feelings about it), it’s a useful option to have.

Future Plans: Adding New Java Features

At the time of writing, Project Lombok was in version 0.8.5. The Lombok team’s short-term goal was to stabilize Lombok and make it fault-free in Eclipse. Although I’ve had some minor issues with the early versions (e.g., some unexpected compilation warnings), simply recompiling the project got rid of them quickly. Overall, the benefits of using Lombok far outweigh any occasional Eclipse hiccups (which were quite rare, in my experience).

The long-term Lombok plans are far more grandiose. The two Project Lombok authors (Reinier Zwitserloot and Roel Spilker) want to intercept the Eclipse compilation process to the point where they can actually add new features to Java, particularly real closures. Read more about this ambitious goal at this Google Groups thread.

The Downsides

The main downside of Lombok is obvious: the development-time support works only in Eclipse. If Eclipse is not your IDE, then for now Project Lombok is not an option for you. You’ll be able to add NetBeans and IntelliJ support in the future, but it will involve some pretty heavy IDE-specific hacking.

However, all Eclipse shops should look into adding Lombok into their daily tool chains today.

Bye-bye POJO Verbosity

With the introduction of Project Lombok, Reiner and Roel have made Java POJO verbosity history. When you add Lombok to your daily coding practices, there just isn’t any going back. It’s that simple. In my opinion, it’s the most revolutionary addition to the Java ecosystem since the arrival of Eclipse itself.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

Top 5 B2B SaaS Marketing Agencies for 2023

In recent years, the software-as-a-service (SaaS) sector has experienced exponential growth as more and more companies choose cloud-based solutions. Any SaaS company hoping to stay ahead of the curve in this quickly changing industry needs to invest in effective marketing. So selecting the best marketing agency can mean the difference

technology leadership

Why the World Needs More Technology Leadership

As a fact, technology has touched every single aspect of our lives. And there are some technology giants in today’s world which have been frequently opined to have a strong influence on recent overall technological influence. Moreover, those tech giants have popular technology leaders leading the companies toward achieving greatness.

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.