Saturday, August 27, 2011

Automatically Generate Get and Set Methods with Project Lombok



A Java Data Object is typically a simple class containing boiler-plated set/get method code. Sure we can manually type-in these boiler-plated code or let our Java IDE generate it for us. But boiler-plated code is bad, how can we easily see if it's a normal data-class? How about let's just define the fields (like in Groovy on Grails) and let the compiler generate all the boiler-plated code we need? With Project Lombok annotation processor we can tell the Java compiler to generate all these boiler-plated code. OK, let's try it. Checkout my example here.


(1) WE DEFINE ONLY THE DATA FIELDS.


(2) SEE THE NAVIGATOR CONTAINING ONLY OUR DEFINE FIELDS.


(3) I REFERENCE lombok.jar AND ADD lombok.Data ANNOTATIONS.


(4) AND SEE THE COMPILER AUTOMATICALLY GENERATES  ALL THE BOILER-PLATE CODE I NEED =)

And it works! We just add the lombok.Data annotations in our class definition and it tells the compiler to automatically generate the stuff we need. By using the Project Lombok, we can throw all that boiler-plate code stuff away! =)

There's more! See also:
Reducing Boilerplate Code with Project Lombok

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.