What is Lombok?
Lombok is a Java library that auto generates lots of boiler plate code for Java classes. Lombok works at compile time and manipulates Java byte code to add additional features. Lombok uses annotations to specify what boiler plate code will be generates.
Using @Setter and @Getter annotations
Lombok provides @Setter and @Getter annotations, that can be applied to any class to automatically generate Setter and Getter methods for all the variables in that class. @Setter annotation is smart enough, that it will not generate setter methods for final fields.
Below let's see an example of how to use @Setter and @Getter annotation to auto generate setter and getter methods for a Java object.
Define POJO class as below:
package com.blogspot.devnip.lombok.settergetter; import lombok.Getter; import lombok.Setter; import java.time.LocalDate; public class SimpleObject { private String name; private LocalDate dateOfBirth; }
Now we can simple invoke setter and getter methods, without even defining them. You might need to add Lombok plugins to your IDEs to get this to work
package com.blogspot.devnip.lombok.settergetter;
import java.time.LocalDate;
public class SetterGetterUsage {
/**
* Create SimpleObject using Lombok generated setter and getters
*
* @return
*/
public static SimpleObject createDummy() {
SimpleObject simpleObject = new SimpleObject();
simpleObject.setName("James Smith");
simpleObject.setDateOfBirth(LocalDate.of(1980, 11, 27));
return simpleObject;
}
}
All the posts in this blog have a working example. Please visit our Github repository
0 comments:
Post a Comment