Lombok introduces how to eliminate Java's lengthy
Lombok is a Java utility that can be used to help developers eliminate Java longness, especially for simple Java objects (POJO ).
It achieves this goal through annotations. A standard Java bean generally has several attributes, each of which has the getter () and setter () methods,
Usually there is also a toString () method, an equals () method, and a hashCode () method. In this way, the code is redundant.
Install Lombok
To use Lombok, you must first install it. This example describes how to install myeclipse. First download lombok. jar from the official website.
Copy lombok. jar to the directory where myeclipse. ini/eclipse. ini is located.
Open myeclipse. ini/eclipse. ini, add the following two lines at the end, and save:
-Xbootclasspath/a: lombok. jar
-Javaagent: lombok. jar
Restart myeclipse/eclipse.
Use Lombok
Now you can use Lombok in IDE. Check the following code:
public class User { private String username; private String password; private int age;}
The above is a typical start of a simple Java bean. You can add getters and setters for each attribute.
Then add an equals () method, a toString () method, and a hashCode () method.
With Lombok, you do not need to perform the preceding operations on your own. Instead, you only need to add a comment:@Data.
@Datapublic class User { private String username; private String password; private int age;}
Lombok Annotation
For more information about Lombok annotations, see the help documentation.
The following describes several commonly used lombok annotations.
@ Data: Annotation on the class; provides the getting and setting methods for all attributes of the class, and also provides the equals, canEqual, hashCode, and toString methods.
@ Setter: Annotation on the property; provides the setting method for the property
@ Getter: Annotation on the property; provides the getting method for the property
@ Log4j: Annotation on the class; provides a log4j log object named log for the class.
@ NoArgsConstructor: Annotation on the class; provides a construction method without parameters for the class
@ AllArgsConstructor: Annotation on the class; provides a constructor for the class.
When using annotations, let's see what Lombok has done.
public class User { private @Getter @Setter String username; private @Getter @Setter String password; private @Getter @Setter int age;}
You can even write it like this:
@Datapublic class User { private String username; private String password; private int age;}
It can be seen that during the compilation period, Lombok adds getter setter, even hashCode, equals, and toString to all attributes based on the written annotation.