June 29, 2013

Java syntax sugar with Project Lombok

0  comments

In one of my last projects I used Project Lombok to reduce boilerplate code. Lombok provides some annotations to remove the noise from the java language.

How does it work

Lombok runs as as an annotation processor which handler modifies the AST (Abstract Syntax Tree) by injecting new nodes such as methods and fields. After the annotation processing stage, the compiler will generate byte code from the modified AST.

How do I use it

Getters and setters like:
private String name = "Jens";

public String getName(){
  return name;
}

public String setName(String name){
  this.name = name;
}
Can be replaced by the Lombok annotations:
  @Getter @Setter private String name = "Jens";
Or replace the noisy initialization of a logger:
public class MyClass {
   private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MyClass.class);
   
   public static void main(String... args) {
     log.error("Log me tender, log me sweet, ...");
   }
}
With a fancy annotation:
@Log
public class LogExample {  
 public static void main(String... args) {
     log.error("Log me tender, log me sweet, ...");
 }
}
There are a lot more lombok features. There is also a great tutorial. What lombok does is not very impressive when you look at just a single example. But it helps a lot to remove java syntax noise from your classes and focus on the important parts of your business logic. When you look at the @data example, you can imagine how much code you don't have to write(generate), read and maintain with Lombok.

Installation

Lombok can be installed with maven or ivy or include the lombok.jar in you build path. You have to teach your IDE about Lombok. Double click on the lombok.jar to install it into eclipse. For IntelliJ there is plugin available. It can also be installed from the IntelliJ plugin repository.

Summary

No more java projekts without Lombok.

Tags

boilerplate, Java, Lombok, syntax sugar


You may also like

Blog url changed to https

I just changed the url of this blog to https://jensjaeger.com. TLS encryption is now the default for all request to this page. It might be possible that some image links on some articles are hard coded http. If you find such an error it would be nice if you leave me comment so i can

Read More

Format date and time in java with prettytime

Prettytime is a nice java library to format a java Date()s in a nice humanized ago format, like: moments ago 2 minutes ago 13 hours ago 7 months ago 2 years ago Prettytime is localized in over 30 languages. It’s super simple to use Add the dependency to your maven pom: org.ocpsoft.prettytime prettytime 3.2.7.Final or

Read More