• Home
  • Events
  • About
  • Java Without the Boilerplate – Project Lombok

    Project Lombok is a very cool little Java library that aims (and succeeds) in removing boilerplate, meaningless, and uninteresting code from your Java objects. The basic idea is to replace things like getters and setters with simple annotations, and then let the Java compiler generate the necessary bytecode in the .class file so that tools such as Eclipse and the Java compiler have no idea what anything unusual happened. Lombok hooks into the compiler to make sure this happens correctly.

    First we’ll cover some Lombok basics and then show how it can be used with the Canoo RIA Suite (ULC) project and and view generators. This includes details on how to mix Lombok annotated objects with JPA annotations, which you might want to glance at before leaving!

    Update: You do not need ULC to work with Lombok. The two are separate projects.

    Lombok in Action
    So let’s see Lombok in action. Consider this Java class that includes a Lombok annotation:

    OK, so there is an @Data annotation in there. So what? Well, to javac and tools (like Eclipse) this class has getters and setters for all three fields, an equals and hashcode implementation, and a toString method. Eclipse tools still give you autocomplete the Navigator shows the correct methods. Not only did you not have to write (or generate) the code yourself, but you don’t have to see that code when coming back in maintenance mode. The interesting bits of your class are no longer buried in the noise. Consider what this looks like without lombok:

    That’s a lot of code for something so simple. It doesn’t even fit in my browser margins without funky line breaks! Sure, IDEs can generate it for you. But what if something interesting is buried in the equals() method? Or perhaps a setter has a side-effect? You can’t easily see this with the reams of boilerplate typical of Java. With lombok, only the essentials are displayed, so the unique parts of the object will stand out to the future reader. And yes, even using @Data you are free to provide your own implementations for any of these methods.

    Richard Gabriel made this observation when comparing old programs (like MacPaint) to “modern” programs writen in langauges like Java:

    I’m always delighted by the light touch and stillness of early programming languages. Not much text; a lot gets done. Old programs read like quite conversations between a well-spoken research worker and a well-studied mechanical colleague, not as a debate with a compiler. Who’d have guessed sophistication brought such noise.

    Now, with Lombok, sophistication is finally taking the noise away, rather than adding to it.

    Just a couple important details before moving on to a Lombok example that uses Canoo’s RIA Suite

  • Lombok is compile time only. It does not need to be deployed with your app
  • Lombok works with javac and Eclipse. IntelliJ IDEA will not ‘see’ the added methods
  • lombok.jar contains an installer that configures your eclipse.ini file correctly. Be sure to run “java -jar lombok.jar” after you download it (especially for those on 64 bit Linux like me)
  • Lombok with Canoo RIA Suite
    The point of this was to make sure I could use Lombok on my next RIA Suite(aka ULC) project. It’s looks like I can, and you can too. To prove it, let’s generate a RIA Suite project, add a domain class using Lombok, generate the views, and run the application.

    Prerequisites

  • Install Eclipse for Java EE Developers. Make sure that you have for Java EE developers.
  • Install Canoo RIA Suite. Get your download and evaluation key from our customer portal.
  • Install Lombok. Download it and run “java -jar lombok.jar”.
  • Steps
    Here are the steps we’ll perform to get this thing working:

  • Generate a Project using ULC’s Project Generator in Eclipse
  • Add the lombok Jar to your project
  • Create a domain object called Contact and annotate it with @Data
  • Generate the views using ULC’s generate-beans-view in Eclipse
  • Run the app and behold a default, thin client, CRUD application
  • Generate the Project
    The ULC Application Development Guide contains a 10 page getting started tutorial that walks you through the process from starting at zero and going to a deployed RIA Suite application. Really, it is quite simple. You just need to add the Project Generator as an external tool in Eclipse. Although it is a bunch of screenshots, this is a common task for Eclipse users and little can go wrong.

    In Eclipse, click Run -> External Tools > Open External Tools Dialog… and point a new external tool to your “/addon/generators/build-setup.xml” from the RIA Suite install. Your window should look like this:

    0ToolConfiguration

    Now you’ll have the menu entry for Run -> External Tools -> ULC Project Generator, which you should click now. You’ll be prompted for a project name and whatnot, and a sample Contacts application will look like this:

    1GenerateProject

    The script runs and you now have a project on disk that can be run. Just click to File -> Import to import it, navigating to where it is on disk. Your import screen should look like this:

    2ImportProoject

    If it all goes well your project should be open and your Project Explorer should look like this:

    3ProjectView

    Add the Lombok Jar
    We need to add the lombok.jar to the Contacts project, add it to the build classpath, and click Refresh to make sure Eclipse is aware that something changed.

    Copy the lombok.jar to ./Contacts/lib/development directory in your project. Then edit the project properties (right click the Contacts project and select Properties), select the Java Build Path entry, and add lombok.jar as a Jar. Should look like this:

    4AddLibrary

    Create Domain Object
    Let’s add a domain object with JPA persistence to our project. A Contacts application must show a Contact, right? This looks about right:

    Let me explain a few details… The class is marked @Entity so that JPA persistence works. The class will map to a Contact table in the database. The class is marked @Data so that lombok will weave in getters, setters, toString, equals, and hashcode methods. The @Id annotation on the “id” field marks that field as the primary key to JPA, and the @GeneratedValue means the field auto increments. I use the GenerationType.SEQUENCE strategy because I plan on deploying to Google App Engine, otherwise this parameter here is unneeded. Lastly, getters and setters are supressed on the id field by adding @Getter(AccessLevel.NONE) and @Setter(AccessLevel.NONE). If you don’t do this then the view-layer automation of Ria Suite is going to, by default, provide you with edit fields for the id, which you should not do.

    Generate the View Layer
    To generate the view layer, click Run -> External Tools -> “Contacts generate-beans-view”. This tool was installed for you by the Project Generator. Running it generates a simple Create-Read-Update-Delete (CRUD) interface with a table, buttons, and entry editor. You’ll see a couple new classes and property files in your application after you run the tool.

    Run application
    Last thing to do is run the app. Click Run -> Run History -> Contacts (again installed by the project generator), sit back, and behold an application.

    5DeployedApp

    That’s it!

    Next step is to deploy to Google App Engine using that Contacts-copy-to-GoogleApp tool that the generator installed, but that is a blog post (and task) for another day.

    Enjoy!

    Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
    • DZone
    • Y!GG
    • Webnews
    • Digg
    • del.icio.us
    • DotNetKicks
    • Facebook
    • Google Bookmarks
    • Newsrider
    • Twitter
    • YahooBuzz

    13 Comments »

    1. Michal said,

      July 27, 2010 @ 13:48

      I used it and I don’t recommend it. Yes, it reduces the boilerplate. But on the other hand, it makes your project not portable, because people have to install Lombok for it to work. And it messes around with the Java compiler, it’s pretty evil to me.

    2. Hamlet said,

      July 27, 2010 @ 14:15

      Thanks for the feedback Michal. I have to admit I do not have any “lombokized” code running in production… this type of feedback is good to hear as we are making decisions now about the next project.

    3. Roel Spilker said,

      July 27, 2010 @ 22:39

      Thanks for the great review. I’m glad our products work so well together.

      If you are afraid to use Lombok in production code, you should know that there is also the delombok tool included in the jar. You can always use delombok to transform your source files including lombok annotations to the lombokless counterparts.

      I hope that takes away some of the scare…

      Roel

    4. Jero said,

      July 28, 2010 @ 11:42

      In addition to the remarks Michal made, it also makes refactoring a pain. Eclipse won’t update your references to getters and setters if you rename properties. Another (minor) thing is that using Lombok does not enable you to specify comments for generated getters/setters. You can comment the fields instead, but this won’t be visible in the generated javadoc.

    5. Tom said,

      July 28, 2010 @ 13:16

      public class Contact {
      public String name;
      public String email;
      public String primaryPhone;
      }

      There, fixed it for you, no Lombok required.

    6. h121 said,

      July 28, 2010 @ 18:56

      Pretty nice, but is Canoo a dependency? What if I wanted to use something else (eg. Vaadin)?

    7. Greg said,

      July 28, 2010 @ 22:33

      I think thats neat but if I wanted that then I would just make the data elements public. The generated code doesn’t do anything to protect the data anyway. And I rarely want an equals method that compares every single field.

    8. assd said,

      July 29, 2010 @ 5:29

      Tom, it’s great! I also think, that using very simple properties, like …{get { return filed; } ; set { field=value; } } is useless ad stupid. just uset the field, if you dont do anything more complicated (thread locks, data manipulation, filtering lists…}

    9. Hamlet said,

      July 29, 2010 @ 8:27

      Canoo is not a dependency. The two projects are in no way coupled.

      There is a way to customize the equals() implementation to include/exclude certain fields. I just explained it here with a simple example.

      Lombok has quite a few more annotations than just @Data. There website has very good (and short) documentation.

    10. Willie Wheeler said,

      July 30, 2010 @ 7:21

      Sounds very interesting. I am glad to see the Java community chipping away at all the boilerplate like this.

      How does Lombok compare to Spring Roo? Roo uses AspectJ ITDs to factor out the same sort of boilerplate (e.g. JavaBeans getters/setters, JPA entity annotations, toString(), etc.).

    11. Hamlet said,

      July 30, 2010 @ 7:55

      @Willie I’m talking about Lombok, Spring Roo, and Groovy AST Transforms at Java One and 2GX this year, so try to make it out and see if you want.

      How does Lombok and Roo compare? They are totally different. Roo aims to be an entire platform for web development and Lombok has much smaller aims. As for what Lombok does technically, “iirekm” left a comment on the DZone link saying this:

      Lombok doesn’t directly generate any bytecode – for generating/changing bytecode tools like AspectJ / CGLIB / BCEL / ObjectWeb ASM exist.
      Lombok attaches to Annotation Processor Tool, uses reflection to acces compiler’s Abstract Syntax Tree and modifies it, and then compiler after some phases generates bytecode.
      Lombok unfortunately isn’t perfect:
      - it is unportable – currently it works only with Eclipse and Oracle’s javac; what about IntelliJ / NetBeans / Jikes people?
      - I don’t know how now, but when I looked at its source code a few months ago, it wasn’t easy to add custom ‘generators’ to Lombok – every good tool should be extensible – Lombok isn’t

    12. Roel Spilker said,

      August 24, 2010 @ 22:43

      Actually, Lombok is extensible. You can provide your own transformations if you want to. Just write itm compile it and add it to the classpath. NetBeans is supported as well. NetBeans 6.8 kinda worked; 6.9 support is great.

      In an upcoming version it is even simpler to create your own extensions; currently you have to provide an Eclipse and a javac implementation. We’re working very hard to make it possible to write your transformation once and the Lombok does the heavy lifting to make it work on all supported platforms. We hope to support IntelliJ in the near future.

    13. Anthony Whitford said,

      September 11, 2010 @ 17:50

      A Maven plugin for delombok has been recently introduced: http://awhitford.github.com/lombok.maven/

    RSS feed for comments on this post · TrackBack URI

    Leave a Comment


    three + 8 =

    css.php