preface

What? Is your Java code still riddled with set/get methods?

As we said when we first started learning the Java language, the three main characteristics of object orientation are encapsulation, inheritance, and polymorphism. In Java, to ensure encapsulation, it is necessary to privatize member variables and provide set/ GET methods to access them. Although modern IDES, such as Eclipse and IDEA, provide shortcuts to generate set/ GET methods, when doing projects, A JavaBean tends to have a lot of member variables, one variable for two methods, or if you have more than 10 member variables for more than 20 methods, and you may need to write constructors, equals, etc., and maintain them. This can make the code very redundant, which is very verbose and not very technical, and it’s easy to forget to change the corresponding method once you change the attribute.

When I was looking at the source code for the big guy’s project, I was intrigued to see that they didn’t have set/ GET methods in their code, instead they had annotations on Javabeans. It turned out that they were using a plug-in called Lombok, so I went to learn more about it.

Background on Lombok

The official introduction is as follows:

Project Lombok makes java a spicier language by adding 'handlers' that know how to build and compile simple, boilerplate-free, not-quite-java code.
Copy the code

Lombok makes Java simple and fast by adding “handlers”.

Use of Lombok

Lombok automatically generates constructors, getters/setters, equals, hashcode, and toString methods for properties at compile time via annotations. The magic that happens is that there are no getters and setters in the source code, but there are getters and setters in the bytecode files generated by the compilation. This saves you the trouble of manually rebuilding the code and makes it look cleaner.

Lombok use as reference jar package, can in the website (https://projectlombok.org/download) to download the jar package, also can use maven add depends on:

< the dependency > < groupId > org. Projectlombok < / groupId > < artifactId > lombok < / artifactId > < version > 1.18.10 < / version > <scope>provided</scope> </dependency>Copy the code

Note: There are a few steps to configuring the Lombok plug-in for the first time

  • Install Lombok into IDEA File -> Setting Select Plugins, search for Lombok, and click Install
  • Choose javac as the default compilation method because Eclipse does not support Lombok compilation and Javac supports Lombok compilation.
  • Enable annotation Processing

Note again: IntelliJ IDEA 2019.2 (the version I used) does not support Lombok plug-ins by default, Need to go to https://plugins.jetbrains.com/plugin/6317-lombok/versions to download the corresponding version of the plugin, then introduce manually, Go to File -> Setting -> plugins to find Install Plugin from Disk… (Note that the version may vary by location)

Let’s look at the specific use of annotations in Lombok

@data @data annotation On a class, setter/getter, equals, canEqual, hashCode, toString methods are automatically generated for all properties of the class. If the property is final, no setter methods are generated for that property. Let’s say we write a student class

@Data
public class Student {

    private String name;

    private Integer age;

    private Integer id;

    private String major;

}
Copy the code

This allows you to call the set/get method.

@getter / @setter If @data seems too tyranous (because @data combines @toString, @equalSandhashCode, @getter / @setter, @requiredargsconstructor) You can use the @getter / @setter annotation on a property that automatically generates set/get methods for the property.

public class Student {
   @Setter private String name;

    private Integer age;

    private Integer id;

    private String major;

    public static void main(String[] args) {

        Student stu = new Student();

        stu.setName("Mr.ml"); }}Copy the code

@nonNULL This annotation is used on attributes or constructors, and Lombok generates a non-null declaration that can be used to validate parameters, helping to avoid null Pointers.

public class Student { @Setter private String name; private Integer age; private Integer id; private String major; public Student(@NonNull String name) { this.name = name; }}Copy the code

Cleanup This annotation helps us automatically call the close() method, greatly simplifying the code.

public class CleanupExample {
  public static void main(String[] args) throws IOException {

  @Cleanup InputStream in = new FileInputStream(args[0]);

  @Cleanup OutputStream out = new FileOutputStream(args[1]);

  byte[] b = new byte[10000];

  while (true) {

   int r = in.read(b);

        if (r == -1) break; out.write(b, 0, r); }}}Copy the code

@equalSandHashCode By default, all non-static and non-transient attributes are used to generate equals and hashCode, as well as exclude attributes.

@EqualsAndHashCode(exclude={"id"."shape"})
public class EqualsAndHashCodeExample {

    private transient int transientVar = 10;

    private String name;

    private double score;

    private Shape shape = new Square(5, 10);

    private String[] tags;

    private int id;

    public String getName() {

        return this.name;

    }

    @EqualsAndHashCode(callSuper=true) public static class Square extends Shape { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; }}}Copy the code

The @toString class uses the @ToString annotation, and Lombok generates a ToString () method that, by default, prints the class name, all the attributes (in the order they are defined), separated by commas. By setting the includeFieldNames parameter to true, you can explicitly output the toString() attribute. If this point is a bit convoluted, the code will make it clearer.

@ToString(exclude="id")
public class ToStringExample {

    private static final int STATIC_VAR = 10;

    private String name;

    private Shape shape = new Square(5, 10);

    private String[] tags;

    private int id;

    public String getName() {

        return this.getName();

    }

    @ToString(callSuper=true, includeFieldNames=true) public static class Square extends Shape { private final int width, height; public Square(int width, int height) { this.width = width; this.height = height; }}}Copy the code

NoArgsConstructor, @requiredargsconstructor and @allargsconstructor No parameter constructor, partial parameter constructor, full parameter constructor. Lombok does not allow multiple parameter constructors to be overloaded.

@RequiredArgsConstructor(staticName = "of") @AllArgsConstructor(access = AccessLevel.PROTECTED) public class ConstructorExample<T> { private int x, y; @NonNull private T description; @NoArgsConstructor public static class NoArgsExample { @NonNull private String field; }}Copy the code

Source: Mr. Ml



Welcome to follow my wechat public account “Code farming breakthrough”, share Python, Java, big data, machine learning, artificial intelligence and other technologies, pay attention to code farming technology improvement, career breakthrough, thinking transition, 200,000 + code farming growth charge first stop, accompany you have a dream to grow together