Project Lombok: Let’s not mess up our java source code writing getters and setters over and over

You java guys probably bored writing getter and setter over and over. You want something like c# get; set; feature. I think here I can help you. There is a project named, “Project Lombok”.

With this, you won’t need to write getters and setters any more. Lombok will do it for you.

To get the things running you need to follow me:

–          Download Lombok:  http://projectlombok.org/download.html

–          Get the jar, double click on it; it will do everything for you, but just to be sure, read what is written in there.

–          Now in your eclipse/netbeans/sts, you need to add the Lombok jar at project classpath, that’s all, no big deal. Create a folder in your project, name it libs, and paste the lobbok .jar on it. Now click on the project, select properties, select java build path and then click on the libraries and then click on Add JARs.

We are done; now let’s see an example –

let’s write a class named Product :


public class Product {
@Getter
@Setter
private int productId;
@Getter
@Setter
private String name;
@Getter
@Setter
private String Description;
@Getter
@Setter
private BigDecimal Price;
@Getter
@Setter
private String Category;

@Override
public String toString() {
return "Product [productId=" + productId + ", name=" + name
+ ", Description=" + Description + ", Price=" + Price
+ ", Category=" + Category + "]";
}
}

see, there are only @Getter and @Setter annotations, no bunch of getters and setters. Now lets see how we can access these..


public class Apps {
public static void main(String[] args) {
Product p = new Product();

p.setProductId(1);
p.setName("java");
p.setDescription("java programmers are monkey");
p.setPrice(new BigDecimal(1000));
p.setCategory("Programming language");

System.out.println(p.toString());

}
}

Wow.. It just works. Everything is just fine as before. We can access our attributes through getter and setter, but we didn’t write it. The Project Lombok takes care of these getters and setters. It generate these boilerplate setters and getters into the compiled code without messing up your source code.

I think it is something really interesting.

It has more interesting features, try it: http://projectlombok.org/features/index.html

NOTE: Lombok only works with java 6 or higher version.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s