Make good use of this idea plug-in and improve the efficiency of writing code by at least 5 times!

Time:2021-12-18

Are you still writing boring and difficult to maintain POJOs? Where is the spring of cleanliness addicts? Look at Lombok!

In past Java projects, there were too many unfriendly Codes: getter / setter / toString of POJO; Exception handling; The closing operation of I / O flow and so on. These template codes have no technical content and affect the beauty of the code. Lombok came into being.

First of all, let’s explain that the emergence of any technology is to solve a certain kind of problems. If you build tricks on this basis, it’s better to return to Java itself. Reasonable use should be maintained without abuse.

Lombok is very simple to use. Let’s take a look at it together:

1) Introduce the corresponding Maven package:

org.projectlombok
  lombok
  1.16.18
  provided

Lombok’s scope = provided indicates that it only takes effect at the compilation stage and does not need to be entered into the package. In fact, Lombok correctly compiles java files annotated with Lombok into complete class files at compile time.

2) Add ide tool support for Lombok:

Lombok support introduced in idea is as follows:

Click file — settings to install Lombok plug-in:

Click the file — settings setting interface to open the annotation processors:

This item is enabled to allow Lombok annotations to work at compile time.

The Lombok plug-in of eclipse can be installed by itself. It is also relatively simple. It is worth mentioning that the built-in compiler of eclipse is not Oracle javac, but eclipse compiler for Java (ECJ) implemented by eclipse itself In order for ECJ to support Lombok, you need to Add the following two items to the INI configuration file:

-Xbootclasspath / A: [Lombok. Jar path]

-Javaagent: [Lombok. Jar path]

3) Lombok implementation principle:

Since Java 6, javac has supported the “JSR 269 pluggable annotation processing API” specification. As long as the program implements the API, it can be called when javac is running.

Lombok is a program that implements the “JSR 269 API”. In the process of using javac, the specific process of its effect is as follows:

  • Javac analyzes the source code and generates an abstract syntax tree (AST)
  • In the javac compilation process, the Lombok program that implements JSR 269 is called.
  • At this time, Lombok processes the ast obtained in the first step, finds the syntax tree (AST) corresponding to the class of Lombok annotation, then modifies the syntax tree (AST) and adds the corresponding tree node defined by Lombok annotation
  • Javac uses the modified abstract syntax tree (AST) to generate bytecode files

4) Use of Lombok annotations:

Common notes of POJO class:

@Getter/@Setter:Generate getter / setter methods of all member variables on the action class; Act on a member variable to generate the getter / setter method of the member variable. You can set access permissions and lazy loading.

package com.trace;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

/**
 * Created by Trace on 2018/5/19.
 *Desc: test class
 */
@SuppressWarnings("unused")
public class TestClass {

    public static void main(String[] args) {

    }


    @Getter(value = AccessLevel.PUBLIC)
    @Setter(value = AccessLevel.PUBLIC)
    public static class Person {
        private String name;
        private int age;
        private boolean friendly;
    }


    public static class Animal {
        private String name;
        private int age;
        @Getter @Setter private boolean funny;
    }
    
}

In the structure view, you can see that getter / setter and other methods have been generated:

The compiled code is as follows: [this is also the template code that needs to be written for traditional Java programming]

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.trace;

public class TestClass {
    public TestClass() {
    }

    public static void main(String[] args) {
    }

    public static class Animal {
        private String name;
        private int age;
        private boolean funny;

        public Animal() {
        }

        public boolean isFunny() {
            return this.funny;
        }

        public void setFunny(boolean funny) {
            this.funny = funny;
        }
    }

    public static class Person {
        private String name;
        private int age;
        private boolean friendly;

        public Person() {
        }

        public String getName() {
            return this.name;
        }

        public int getAge() {
            return this.age;
        }

        public boolean isFriendly() {
            return this.friendly;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public void setFriendly(boolean friendly) {
            this.friendly = friendly;
        }
    }
}

@ToString:It acts on the class and overrides the default toString () method. You can limit the display of some fields through the of attribute and exclude some fields through the exclude attribute.

@EqualsAndHashCode:Acts on the class, overriding the default equals and hashcode

@NonNull:It is mainly used in member variables and parameters. The ID cannot be empty, otherwise a null pointer exception will be thrown.

@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor:Acts on a class to generate a constructor. There are staticname, access and other attributes.

Once the staticname property is set, the instance will be generated in a static way, and the access property can limit the access permission.

@Noargsconstructor: generate a parameterless constructor;

@Requiredargsconstructor: constructor that generates member variables containing final and @ nonnull annotations;

@Allargsconstructor: generates a full parameter constructor.

Compiled results:

public static class Person {
    @NonNull
    private String name;
    private int age;
    private boolean friendly;

    public String toString() {
        return "TestClass.Person(name=" + this.getName() + ", age=" + this.getAge() + ")";
    }

    @NonNull
    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }

    public boolean isFriendly() {
        return this.friendly;
    }

    public void setName(@NonNull String name) {
        if(name == null) {
            throw new NullPointerException("name");
        } else {
            this.name = name;
        }
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setFriendly(boolean friendly) {
        this.friendly = friendly;
    }

    private Person() {
    }

    private static TestClass.Person of() {
        return new TestClass.Person();
    }

    @ConstructorProperties({"name"})
    Person(@NonNull String name) {
        if(name == null) {
            throw new NullPointerException("name");
        } else {
            this.name = name;
        }
    }

    @ConstructorProperties({"name", "age", "friendly"})
    public Person(@NonNull String name, int age, boolean friendly) {
        if(name == null) {
            throw new NullPointerException("name");
        } else {
            this.name = name;
            this.age = age;
            this.friendly = friendly;
        }
    }
}

@Data:Acting on a class, it is a collection of the following annotations: @ toString @ equalsandhashcode @ getter @ setter @ requiredargsconstructor

@Builder:Act on classes and transform classes into builder patterns

@Log:Act on the class to generate log variables. There are different annotations for different log implementation products:

Other important notes:

@Cleanup:Automatically close resources for Java io. The object of the closeable interface is valid, such as a typical IO stream object

The compiled results are as follows:

Is it too concise.

@SneakyThrows:The detected exception can be caught and thrown, and the above main method can be rewritten as follows:

@Synchronized:Acting at the method level, you can replace the synchronize keyword or lock lock, which is of little use.

Author: liwend is digging for gold
Link:https://juejin.cn/post/6844903607985242120

Recent hot article recommendations:

1.1000 + java interview questions and answers (2021 latest version)

2.Stop playing if / else on the full screen. Try the strategy mode. It’s really fragrant!!

3.what the fuck! What is the new syntax of XX ≠ null in Java?

4.Spring boot 2.5 heavy release, dark mode is too explosive!

5.Java development manual (Songshan version) is the latest release. Download it quickly!

Feel good, don’t forget to like + forward!