Project Lombok: Put an End to Java Verbosity

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.

devx-admin

devx-admin

Share the Post:
Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

Semiconductor Stock Plummet

Dramatic Downturn in Semiconductor Stocks Looms

Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields such as artificial intelligence. The

Lagos Migration

Middle-Class Migration: Undermining Democracy?

As the middle class in Lagos, Nigeria, increasingly migrates to private communities, a PhD scholar from a leading technology institute has been investigating the impact of this development on democratic

AI Software Development

ChatGPT is Now Making Video Games

Pietro Schirano’s foray into using ChatGPT, an AI tool for programming, has opened up new vistas in game and software development. As design lead at business finance firm Brex, Schirano

Llama Codebot

Developers! Here’s Your Chatbot

Meta Platforms has recently unveiled Code Llama, a free chatbot designed to aid developers in crafting coding scripts. This large language model (LLM), developed using Meta’s Llama 2 model, serves

Tech Layoffs

Unraveling the Tech Sector’s Historic Job Losses

Throughout 2023, the tech sector has experienced a record-breaking number of job losses, impacting tens of thousands of workers across various companies, including well-established corporations and emerging startups in areas

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power as continuous, 24-hour energy sources.

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a live-streamed discussion, Netanyahu lauded Musk

Urban Gardening

Creating Thriving Cities Through Urban Gardening

The rising popularity of urban gardening is receiving increased recognition for its numerous advantages, as demonstrated in a recent study featured in the Environmental Research Letters journal. Carried out by