Lombok

Java developer? You feel class and method declaration is cumbersome? You want to follow Mr Bloch‘s advice but fret verbose boilerplate code? Look no further than Project Lombok!

Lombok helps you as a Java developer, with mundane tasks such as creating no-args constructors, getters/setters, toString/equals/hashCode-generation and more. All you need to do is to annotate your classes, as described in the manual.

For example, if you put the @Data annotation on your class, you’ll get generated toString, equals, hashCode, getter and setter methods, AND a constructor taking all required fields as parameters. Phew!

Behind the scenes, these are generated by code from the lombok jar-file, which must be on the classpath. Plugins exist for most IDE’s, so it’s easy to get going, here’s what you need for IntelliJ:

  1. Install the lombok plugin from the plugin repository.
  2. Add the maven dependency org.projectlombok:lombok version 0.11.6
  3. Annotate your data classes, and use them, example:
@Data
public class Person {
    private final String name;
    private int ageInYears;
}

public class PersonTest {
    public static void main(String[] args) {
        Person person = new Person("Christian Fogel");
        person.setAgeInYears(145);
        System.out.println(person.getName() + "," + person.getAgeInYears());
        System.out.println(person);
    }
}

The above would, surprisingly, not only compile but also print

    Christian Fogel,145
    Person(name=Christian Fogel, ageInYears=145)

Pretty neat isn’t it? As usual, don’t forget to read the fine print, test your classes thoroughly and beware the development status of the project (as indicated by the version number).

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>