Eliminate Java verbosity the easy way

Lombok is a Java™ utility that enables you to eliminate Java verbosity, specifically with plain old Java objects (POJOs). It does this with the use of annotations. You can save a lot of time constructing methods like hashCode() and equals(), as well as the usual assortment of accessors and mutators, by implementing Lombok in the development environment.

Brian M. Carey, Senior Systems Engineer, Triangle Information Solutions

Photo of Brian CareyBrian Carey is an information systems consultant who specializes in the architecture, design, and implementation of Java enterprise applications.



16 February 2010

Also available in Japanese

What is Lombok?

Lombok is a Java Archive (JAR) file you can use to eliminate verbosity in Java code.

Consider, for example, a standard Java bean. A typical Java bean has several properties. Each property has an accessor and a mutator (getter and setter). There is also usually a toString() method, an equals() method, and a hashCode() method.

If you think about it, that seems like an awful lot of predictable redundancy. If it's implied that each property has a getter and setter, and it usually is, why is it necessary to spell it out?

Enter Lombok. Lombok uses annotations to identify classes and blocks of Java code in an effort to eliminate lines of code. In the aforementioned Java bean example, all of the getters, setters, and the three other methods are implied and included at compile time.

It gets better. If you're using Eclipse or IBM® WebSphere® Studio Application Developer (and if not, you probably should be), you can integrate Lombok into your Java project and get instantaneous development-time results. In other words, the Eclipse compiler recognizes the implied getters/setters immediately, and other Java code can reference those methods.

The immediate advantage, of course, is that you have fewer lines of code, which is always a good thing. Also, if a particular getter or setter requires special attention, you don't have to sift through dozens of lines of code to find the one you are looking for. The code appears cleaner, and there is less redundancy. Everybody wins.

Lombok also enables you to simplify other portions of code — not just Java beans. For example, you can eliminate redundant code in try/catch/finally blocks and in synchronized methods.

Now take a look at exactly how you can make this happen in your own development environment.


Installing Lombok

For installation purposes, this article assumes you are using Eclipse or WebSphere Studio Application Developer. If not, you can still use Lombok; you just can't take advantage of the development-time benefits. You can, however, take advantage of the compile-time benefits.

First of all, open your favorite browser and point your URL to http://projectlombok.org/.

As of this writing, there is a big word in the upper right-hand corner of the page that opens from that URL. That word is "Download!" Click that word and proceed to download lombok.jar. The file requires no extraction, unlike 99 percent of the files you download from other sites.

When you have the file downloaded, you need to execute the JAR file. Open a prompt in your operating system, go to the directory where lombok.jar is installed, and type java -jar lombok.jar.

This assumes that the Java Runtime Environment (JRE) is in your path. If not, you need to add it. Consult the documentation for your particular operating system to learn how to do this.

If you are using Microsoft® Windows®, you may also be able to double-click on the lombok.jar icon. Again, you must be able to execute JARs from within your graphical user interface (GUI).

However you end up doing it, you should ultimately see a Lombok installation screen. The screen asks you where your Eclipse or WebSphere Studio Application Developer executable is located. It is probably defaulted to the correct location. But some of you may need to change the default location.

When you click Install/Update, Lombok is quickly incorporated with your Eclipse development environment. If you are already running Eclipse, you need to shut it down and restart it.


Using Lombok

Now you're ready to actually use Lombok within Eclipse or WebSphere Studio Application Developer. Consider the code in Listing 1.

Listing 1. A good start to a Java bean
public class Lure {
	private String name;
	private int size;
	private String color;
	private String style;
}

This is a typical start to a simple Java bean. From here, you would probably add getters and setters for each of those properties. Then you would probably add an equals() method, a toString() method, and a hashCode() method.

With Lombok, you don't need to do any of that. Instead, you just need to add one annotation: @Data.

Yep. That's it. Listing 2 includes @Data.

Listing 2. A better start to a Java bean
import lombok.Data
public @Data class Lure {
	private String name;
	private int size;
	private String color;
	private String style;
}

Bear in mind that this only works if lombok.jar is in your build path and lombok.Data is imported in the Java class.

If you're viewing the outline of the class in Eclipse or WebSphere Studio Application Developer (usually to the right of the class itself on your screen), you can see that these methods are automatically added to the Lure class.

If you can't see the outline immediately, click on the Window menu in Eclipse, then select Show View. From the flyout menu that appears, select Outline, which should appear on the right-hand side of the screen. The hotkey combination for forcing the outline to appear is Alt+Shift+Q, then O.

If you write another class that instantiates Lure, you immediately have access to Lure's implied methods, such as getName() or setSize(). You also have access to equals(), hashCode(), and toString(). Neat, huh?

If you're not using Eclipse or WebSphere Studio Application Developer, these implied method additions are only recognized when you actually compile the code. So although Lombok can be used without Eclipse or WebSphere Studio Application Developer, it was designed to be integrated with Eclipse or WebSphere Studio Application Developer.

Lombok follows the traditional standard when generating the getter/setter methods. All of the method names are prefixed with get or set and the property names are capitalized. The exception, of course, is if the property is a Boolean. In that case, the getter starts with is, as opposed to get. This is standard practice for Java beans.

Now, suppose you have a Java bean with a special requirement for one of your getters. In the example in Listing 2, it's possible that getStyle() will return a combination of color and size. In that case, you simply code out the getStyle() method as you wish. Lombok examines your code and doesn't create its own version of getStyle based on the property.

Perhaps you have a getter method you don't want to expose publicly. Lombok allows you to enter a parenthetical parameter for that purpose. Listing 3 shows a custom modifier.

Listing 3. A custom modifier
	private String name;
	@Getter(AccessLevel.PROTECTED) private int size;
	private String color;
	private String style;

In this case, the getSize() method is not exposed publicly. It has a protected modifier, so it's only available to derived subclasses and within the Lure class itself.

You may not always want to accept the other defaults Lombok gives you, either. For example, the toString() method simply lists the class name, plus all property names and values in a comma-delimited list. The list appears parenthetically next to the class name.

Suppose, for example, that you don't care about the color when logging the Lure class. To change the default of toString(), you use the ToString annotation.

Listing 4. Modifying toString()
@ToString(exclude="color")
public @Data class Lure {
	private String name;
	private int size;
	private String color;
	private String style;
}

When you print an example of an instantiated Lure class, it appears something like this:

Lure(name=Wishy-Washy, size=1, style=trolling)

Notice how the color is excluded? That's because you told Lombok to exclude it with the annotation.

You can also modify how the equals() and hashCode() methods are handled. Listing 5 should be fairly self-explanatory.

Listing 5. Modifying hashCode()
@EqualsAndHashCode(exclude="style")
public @Data class Lure {
	private String name;
	private int size;
	private String color;
	private String style;
}

In this case, when the equals() and hashCode() methods are generated, the style property is excluded.


Other features

Don't you hate writing try/catch/finally blocks all the time? I know I do. Fortunately, you don't have to with Lombok. This is just one other way in which Lombok eliminates Java verbosity. To eliminate the redundancy of the try/catch/finally blocks, simply use the @Cleanup annotation. See Listing 6.

Listing 6. Using The @Cleanup annotation
public static void main(String[] args) throws IOException {
	@Cleanup InputStream in = new FileInputStream(args[0]);
	@Cleanup OutputStream out = new FileOutputStream(args[1]);
	//write file code goes here
}

That's a lot cleaner than what you usually see in standard Java code. Please note that you still need to throw whatever exception is caught by the invoked code (in this case, IOException).

It's important to note that the code block in Listing 6 not only eliminates the try/catch/finally block but also closes the opened streams. If you're working with objects that use a method other than close() to relinquish resources, you invoke that with a parenthetical alongside the annotation. For example, @Cleanup("relinquish").

Lombok also provides less-verbose means of synchronizing methods. Not surprisingly, this is done with the @Synchronized method.

Listing 7. Using the @Synchronized annotation
@Synchronized
private int foo() {
	//some magic done here
	return 1;
}

In this example, Lombok automatically creates an instance object called $lock and synchronizes the method foo() against that object.

If the method annotated with @Synchronized is static, Lombok automatically creates a class object called $LOCK and synchronizes the method against that object.

You can also specify an object to lock explicitly with a parenthetical parameter. For example, @Synchronized("myObject") synchronizes the method against the object known as myObject. In that case, you have to define it explicitly.


Conclusion

Using Lombok, you can accomplish something that all application developers strive to do as much as possible: eliminate redundancy.

You can also make your code more readable. It becomes much easier to find "special" (that is, not following the typical standard) getter and setter methods in Java beans that have a large number of properties. This is because the special getter/setter methods are the only ones actually coded.

Lombok facilitates cleaner code, greater productivity, and less verbosity. Why not give it a try in your own environment?

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Open source on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, Java technology
ArticleID=467569
ArticleTitle=Eliminate Java verbosity the easy way
publish-date=02162010