Introduction, use, simple analysis and plug-ins for lombok

Learn Lombok.

About POJO

There are closeness and security features in Java object-oriented programming.Closure is the enclosure of domain variables in a class, that is, decorate them with private s.As a result, other classes cannot access the variable.In this way, we enclose these variables within the class, which improves the security of the data.

There are two ways to manipulate these domain variables.The first is through a public-style constructor, or constructor, that assigns values to the variable as soon as the object is instantiated.The second is to assign and value variables through set and get methods.In this way, the security of domain variables can be improved and the encapsulation of domain variables can be guaranteed.(

So when we create POJO classes, we don't hesitate to let the developer generate set, get methods for domain variables.Although we don't add them manually (shortcut keys or menus are generated quickly), it's also annoying to have repetitive generations for each class.And when the variable name or modifier changes, we delete the set, get method, and regenerate, which is a repetitive and tedious operation.Lombok is one of those artifacts that we can use to increase productivity and avoid repetitive operations.

Introduction to Lombok

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

This is an official introduction, meaning that Lombok makes Java programming simple and fast with some special handling.

Use of Lombok

Lombok simplifies Java code writing in the form of simple annotations and improves developer productivity.For example, constructors, getter/setter, equals, hashcode, toString methods are automatically generated for attributes at compile time.This means that getter and setter methods are not required in the source code, but there are getter and setter methods in the compiled byte code file.This saves the hassle of manually rebuilding the code and makes it look simpler.

Using Lombok requires referencing Jar package dependencies, while adding dependencies in Maven is easy.

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
    <scope>provided</scope>
</dependency>

Below are descriptions and uses of some of the commonly used notes provided by Lombok.

@Data annotation

The @Data annotation is used on a class and automatically generates setter/getter, equals, canEqual, hashCode, toString methods for all properties of the class.It is important to note that a setter method will not be generated for a final modifier-modified property.

@Data
public class DataExample {
    private final String name;
    
    @Setter(AccessLevel.PACKAGE)
    private int age;
    
    private double score;
    
    private String[] tags;
  
    @ToString(includeFieldNames=true)
    @Data(staticConstructor="of")
    public static class Exercise<T> {
        private final String name;
        private final T value;
    }
}

It is recommended that you use the @Data annotation as little as possible directly in development, but instead replace it with @Setter, @Getter, @NoArgsConstructor, @AllArgsConstructor, @ToString.

@Getter/@Setter comment

Because @Data combines all the features of @ToString, @EqualsAndHashCode, @Getter/@Setter, @RequiredArgsConstructor and many times we may not need so many features, Lombok provides a more detailed annotation @Getter/@Setter, which automatically generates getter/setter for this property when used on propertiesMethod.

public class GetterSetterExample {
    @Getter
    @Setter
    private int age = 10;
  
    @Setter(AccessLevel.PROTECTED)
    private String name;
    
    @Override
    public String toString() {
        return String.format("%s (age: %d)", name, age);
    }
}

@NonNull comment

The @NonNull annotation is used on attributes or constructors, and Lombok generates a non-empty declaration that can be used to check parameters and help avoid null pointers.

public class NonNullExample extends Something {
    private String name;
    
    public NonNullExample(@NonNull Person person) {
        super("Hello");
        this.name = person.getName();
    }
}

If you do not use the @NonNull annotation, you will need to manually perform a non-null check on the properties/constructors.

public class NonNullExample extends Something {
    private String name;
  
    public NonNullExample(Person person) {
        super("Hello");
        if (person == null) {
            throw new NullPointerException("person");
        }
        this.name = person.getName();
    }
}

@Cleanup comment

The @Cleanup 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);
        }
    }
}

If you do not use the @Lombok annotation, you need to manually call colse() to close the input/output stream.

public class CleanupExample {
    public static void main(String[] args) throws IOException {
        InputStream in = new FileInputStream(args[0]);
        try {
            OutputStream out = new FileOutputStream(args[1]);
            try {
                byte[] b = new byte[10000];
                while (true) {
                    int r = in.read(b);
                    if (r == -1) break;
                        out.write(b, 0, r);
                }
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

@EqualsAndHashCode comment

By default, equals and hasCode are generated using all non-static and non-transient attributes, and some attributes can be excluded by the exclude annotation.

@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;
        }
    }
}

@ToString comment

Using the @ToString annotation on a class, Lombok generates a toString() method that, by default, outputs the class name, all attributes (in the order in which they are defined), separated by commas.

By setting the includeFieldNames parameter to true, the toString() attribute is explicitly output.

@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;
        }
    }
}

Annotations for @NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor

The three notes correspond to parameterless constructors, partial and full constructors, respectively.Lombok cannot overload multiple parameter constructors.

@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;
    }
}

Adding the staticName parameter produces a static method of().

The default generated method event public, if you want to generate methods decorated with other method modifiers, you can set the access parameter.

Lombok simple analysis

The basic principle of Lombok is to automatically generate code by parsing annotations at compile time.JDK5 introduces annotations and provides two ways to parse them, runtime and compile-time.

Runtime Compilation

Annotations that can be resolved at runtime must have the @Retention annotation set to RUNTIME in the annotation definition so that class information using the annotation can be obtained through the Java reflection mechanism.An AnnotatedElement interface is provided in the java.lang.reflect reflection Package, which defines several methods for obtaining annotation information. Class, Constructor, Field, Method, Packagage, and so on, all implement this interface.

Compile-time resolution

There are two mechanisms for compile-time parsing:

1.Annotation Processing Tool(apt)

apt was generated from JDK5, has been marked out of date in JDK7, is not recommended, and has been completely removed in JDK8.Starting with JDK6, you can replace it with the Pluggable Annotation Processing API.apt was replaced for two main reasons: one is that its api is under the non-standard package of com.sun.mirror, and the other is that it is not integrated into javac and requires additional running.

2.Pluggable Annotation Processing API(JSR 269)

JSR 269 has been added from JDK6. As an alternative to apt, it solves two problems of apt. When javac executes, it calls programs that implement the API, so we can make some enhancements to the compiler.

In fact, Lombok is essentially a program that implements the JSR 269 API.

Plugins for Lombok

Lombok's plug-ins are provided to the IDE to make it easier for developers to see Lombok's automatically generated code through annotations when writing source code.

Idea Install Lombok Plugin

Idea can be directly installed by searching for Lombok Plugin s in the Plugins library, which is simple and convenient.

Eclipse Install Lombok Plugin

Eclipes needs to download the plug-in locally from the official website and install it from the command line.

1. Download the Lombok plug-in from the official website: https://projectlombok.org/download.html.

2. Switch the command line to the download directory of the Lombok plug-in and run the command: java-jar lombok.jar.

3. In the pop-up visual interface, select the installation/decompression directory of Eclipse and click Install/Update.

When the installation is complete, Eclipse will have one more lombok.jar file in its installation/decompression path and two lines of Lombok configuration code added to its eclipse.ini configuration file:

-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar

This allows you to see Lombok's automatically generated code in Outline after adding the annotations provided by Lombok.

summary

Lombok is a great thing to do to make your development more efficient, your code simpler, and your maintenance easier.One big disadvantage is that Lombok does not support constructor overloading with multiple parameters.

Also note that manually written code overrides Lombok's automatically generated code.For example, if a getter/setter method is handwritten in the source code, the Lombok-generated getter/setter method is overwritten, or Lombok compiles without generating an existing getter/setter.

 

"If you have to do something you don't like, the best way to do it is to do it as quickly as possible and end it without any follow-up."

Keywords: PHP Lombok Java Eclipse Programming

Added by kaitan on Sat, 27 Jul 2019 03:48:50 +0300