What is Lombok? How do I install Lombok? Lombok uses Lombok in detail Provide annotations to improve the simplicity of the code. Common annotations are an overview :val@Data@Value@Getter@Setter@Getter(lazy=true)@ToString@EqualsAndHashCode@NonNull@Synchronized @no ArgsConstructor@AllArgsConstructor@RequiredArgsConstructor@Cleanup@Log@Accessors@SneakyThrows@Builder

preface

In Java, encapsulation is a very good mechanism, the most common encapsulation is get,set method, whether Intellij idea or Eclipse, both provide a quick shortcut to generate get,set method, it is very convenient to use, In fact, we have a more convenient way, which is -Lombok: a very powerful POJO annotator.

What is Lombok?

Lombok provides simple annotations in the form of annotations to help simplify and eliminate some of the necessary but bloated Java code. Especially with respect to POjos.

How do I install Lombok?

1. Install through IntelliJ’s plug-in center

2, Install the Plugin

3. Finally, when using Lombok annotations, import the Lombok. Jar package into the Project and add dependencies to the POM.xml if you are using a Maven Project.

<dependency>

    <groupId>org.projectlombok</groupId>

    <artifactId>lombok</artifactId>

    <version>1.16.8</version>

</dependency>

Copy the code

Lombok uses a detailed explanation

Lombok provides annotations to improve the simplicity of code. Common annotations are an overview:

  • Val: is used before a local variable, making the variable final
  • @data: Annotations on classes; Provides getting and setting methods for all properties of the class, We also provide equals, canEqual, hashCode, and toString methods, which are equivalent to adding the following annotations @set@getter, @toString, and @EqualSandHashCode together
  • @value: used on a class, is an immutable form of @data, equivalent to adding a final declaration to a property, providing only getters, but not setters
  • @setters, @getters: annotations on classes and properties; Provide setting, getting methods for attributes
  • Getter(lazy=true) : Can replace the classic Double Check Lock boilerplate code
  • @toString: Generates the ToString method, which by default prints the class name, all the attributes, in order, separated by commas.
  • @equalSandHashCode: Implements the equals() and hashCode() methods
  • Builder: Build Builder pattern
  • @ NonNull: this annotation to quickly determine whether is empty, if is empty, it throws Java. Lang. NullPointerException
  • @synchronized: This annotation is automatically added to the synchronization mechanism. Interestingly, the generated code does not lock the method directly, but locks a block of code with scope on the method
  • Log: Generates different types of Log objects based on different annotations, but the instance name is Log. There are six optional implementation classes
  • @noargsconstructor: annotation on class; Generates a static factory method that returns a class object.
  • @requiredargsConstructor: Annotations on classes; A constructor that provides a partial argument for a class (all member variables in the class with @nonnull annotation or final modification are used to generate the corresponding constructor)
  • @allargsconstructor: Annotation on class; A constructor that takes one full parameter for a class
  • Cleanup: Used to ensure that allocated resources are released, such as IO connection closure
  • SneakyThrows an exception
  • @accessors: Used to configure the generated results of getter and setter methods

val

When used before a local variable, it is equivalent to declaring the variable final

public static void main(String[] args) {

    val sets = new HashSet<String>();

    //=> Equivalent to the following

    final Set<String> sets2 = new HashSet<>();

}

Copy the code

@Data

Annotations on classes; Provides getting and setting methods for all properties of the class, We also provide equals, canEqual, hashCode, and toString methods, which are equivalent to adding the following annotations @set@getter, @toString, and @EqualSandHashCode together

@Data

public class Person {

    private String name;

    private String address;

    private String city;

    private String state;

    private String zip;

    private Date brithday;

}

Copy the code

The effect is the same as below:

@Value

@Value

@AllArgsConstructor

public class Student {

    private String name ;

    private int age;

    / / equivalent to

    private final int age;

    public int getAge(a){

        return this.age;

    }

}

Copy the code

Actual call:

Student student = new Student("hresh".22);// There is no set method

System.out.println(student);

System.out.println(student.getName());

Copy the code

@Getter@Setter

Annotations on classes and properties; Provide setting, getting methods for attributes

public class Person {

    @Getter@Setter

    private String name;

}

Copy the code

Is equivalent to:

public String getName(a) {

        return name;

    }



public void setName(String name) {

        this.name = name;

}

Copy the code

@Getter(lazy=true)

If the initialization of a field of the Bean is a costly operation, such as loading a large amount of data; This field is not necessarily used. By using lazy loading, you are guaranteed to save resources.

Lazy loading: when an object is initialized, the field is not initialized, but is initialized the first time the field is accessed.

public class GetterLazyExample {

    @Getter(lazy = true)

    private final double[] cached = expensive();

    private double[] expensive() {

        double[] result = new double[1000000];

        for (int i = 0; i < result.length; i++) {

            result[i] = Math.asin(i);

        }

        return result;

    }

}



// Equivalent to the following:



import java.util.concurrent.atomic.AtomicReference;

public class GetterLazyExample {

    private final AtomicReference<java.lang.Object> cached = new AtomicReference<>();

    public double[] getCached() {

        java.lang.Object value = this.cached.get();

        if (value == null) {

            synchronized (this.cached) {

                value = this.cached.get();

                if (value == null) {

                    final double[] actualValue = expensive();

                    value = actualValue == null ? this.cached : actualValue;

                    this.cached.set(value);

                }

            }

        }

        return (double[]) (value == this.cached ? null : value);

    }

    private double[] expensive() {

        double[] result = new double[1000000];

        for (int i = 0; i < result.length; i++) {

            result[i] = Math.asin(i);

        }

        return result;

    }

}

Copy the code

@ToString

Generate the toString method, which, by default, prints the class name, all the attributes, in order, separated by commas. Note that @toString has several properties that can be further set:

  • callSuperWhether to print the toString method of the parent class. Default is false
  • includeFieldNamesWhether to include the field name. Default is true
  • excludeExclude fields that generate toStrings
@ToString(callSuper = true,exclude ={"name"})

public class Person {

    private String name;

    private String address;

}

Copy the code

Is equivalent to:

public String toString(a) {

 return "Person{" +

                "address='" + address + '\' ' +

    '} ';

}

Copy the code

@EqualsAndHashCode

For classes, automatically generate equals and hashCode methods

The parameter exclude excludes some attributes. The of argument specifies which attributes to use only; By default, only properties defined in the class are used and methods of the superclass are not called (that is, callSuper=false).

/ / parent class

public class Person {

    private String name;

    private String sex;



    public Person(String name, String sex) {

        this.name = name;

        this.sex = sex;

    }

}

Copy the code
@EqualsAndHashCode(exclude = {"className"},callSuper = false)

public class Student extends Person{

    @Getter@Setter

    private int age;

    @Getter@Setter

    private String className;



    public Student(String name,String sex,int age,String className) {

        super(name,sex);

        this.age = age;

        this.className = className;

    }

}

Copy the code
Student s1 = new Student("hresh"."man".22."Lv3");

Student s2 = new Student("hresh"."woman".22."Lv5");

System.out.println(s1.equals(s2));//true

Copy the code

Resolution: A subclass that implements @equalSandHashCode (callSuper = false) does not call the property of the parent class, so if the property of the subclass is the same, the value of hashcode will be the same, plus the exclusion of comparisons to the className property, So the equals method returns true for the two objects in the code.

@NonNull

The annotation to quickly determine whether is empty, if is empty, it throws Java. Lang. NullPointerException

public class Person {



    private String name;



    @Setter@Getter@NonNull

    private List<Person> member;

}

Copy the code

Is equivalent to:

@NonNull

private List<Person> members;



public Family(@NonNull final List<Person> members) {

    if (members == nullthrow new java.lang.NullPointerException("members");

    this.members = members;

}



@NonNull

public List<Person> getMembers(a) {

    return members;

}



public void setMembers(@NonNull final List<Person> members) {

    if (members == nullthrow new java.lang.NullPointerException("members");

    this.members = members;

}

Copy the code

@Synchronized

This annotation is automatically added to the synchronization mechanism. Interestingly, the generated code does not lock the method directly, but rather locks a block of code that is scoped to the method.

private DateFormat format = new SimpleDateFormat("MM-dd-YYYY");



@Synchronized

public String synchronizedFormat(Date date) {

    return format.format(date);

}

Copy the code

Is equivalent to:

private final java.lang.Object $lock = new java.lang.Object[0];

private DateFormat format = new SimpleDateFormat("MM-dd-YYYY");



public String synchronizedFormat(Date date) {

    synchronized ($lock) {

        return format.format(date);

    }

}

Copy the code

@NoArgsConstructor

Annotations on classes; Provides a constructor that takes no arguments for the class

@Data

@NoArgsConstructor(staticName = "init")

public class Student {

    private long id = new Long(0);

    private String name = "";

    private String className = "";

}

Copy the code

Is equivalent to:

@Data

//@NoArgsConstructor(staticName = "init")

public class Student {

    private long id = new Long(0);

    private String name = "";

    private String className = "";



    public static Student init(a){

        return new Student();

    }

}

Copy the code

A call:

public class StudentTest {

    public static void main(String[] args) {

// Student student = new Student(); // Compile error

        Student student = Student.init();

        student.setName("hresh");

        student.setClassName("Lv5");

        System.out.println(student);

    }

}

Copy the code

@AllArgsConstructor

On a class, an annotation provides a constructor with a full parameter for the class

@Data

@AllArgsConstructor

public class Student {

    private long id = new Long(0);

    private String name = "";

    private String className = "";

}

Copy the code

Is equivalent to:

@Data

public class Student {

    private long id = new Long(0);

    private String name = "";

    private String className = "";



    public Student(long id, String name, String className) {

        this.id = id;

        this.name = name;

        this.className = className;

    }

}

Copy the code

@RequiredArgsConstructor

@Data

@RequiredArgsConstructor

public class Student {

    @NonNull

    private long id ;

    @NonNull

    private String name ;

    private String className;



}

Copy the code

Actual call:

Student student = new Student(101."hresh");

System.out.println(student);

Copy the code

@Cleanup

Annotations can be used to ensure that allocated resources are released, such as IO connection closing.

public void testCleanUp(a) {

    try {

        @Cleanup ByteArrayOutputStream baos = new ByteArrayOutputStream();

        baos.write(new byte[] {'Y'.'e'.'s'});

        System.out.println(baos.toString());

    } catch (IOException e) {

        e.printStackTrace();

    }

}

Copy the code

Is equivalent to:

public void testCleanUp(a) {

    try {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {

            baos.write(new byte[] {'Y'.'e'.'s'});

            System.out.println(baos.toString());

        } finally {

            baos.close();

        }

    } catch (IOException e) {

        e.printStackTrace();

    }

}

Copy the code

@Log

@CommonsLog Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);



@Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName());



@Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class);



@Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);



@Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class);



@XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);

Copy the code

I use slF4J log objects more often.

Annotations on classes; Provide a SLF4J log object with a property named log for the class

@Slf4j

public class StudentTest {



    public static void main(String[] args) {

        log.info("Here is some INFO");

    }

}

Copy the code

Is equivalent to:

public class StudentTest {



    public static Logger log = LoggerFactory.getLogger(StudentTest.class);



    public static void main(String[] args) {

        log.info("Here is some INFO");

    }

}

Copy the code

@Accessors

Accessors is used to configure the results of getter and setter methods. The following three properties are described:

1、 fluent

If fluent is set to true, the get/set method is generated without the set/get prefix. The default value is false.

@Data

@Accessors(fluent = true)

public class Student {

    private long id = new Long(0);

    private String name = "";

    private String className = "";



}

Copy the code

The actual call

public class StudentTest {



    public static void main(String[] args) {

        Student student = new Student();

        student.name("hresh");// Equivalent to SetName()

        student.className("Lv5");

        System.out.println(student);

        System.out.println(student.name());// Equivalent to getName()

    }

}

Copy the code

2、 chain

The Chinese meaning of chain is a Boolean value. The set method generated for true returns this, and the set method generated for false is of type void. The default is false, except when fluent is true, chain defaults to true.

@Data

@Accessors(chain = true)

public class Student {

    private long id = new Long(0);

    private String name = "";

    private String className = "";



}

Copy the code

Actual call:

public class StudentTest {



    public static void main(String[] args) {

        Student student = new Student();



        Student student1 = student.setClassName("Lv5");

        System.out.println(student);

        System.out.println(student1);

    }

}

Copy the code

3, the prefix

Prefix is a series of strings. You can specify a prefix, but the specified prefix is removed when the get/set method is generated.

@Data

@Accessors(prefix = "n")

public class Student {

// private long id = new Long(0);

    private String nAme = "";

    private String name = "";

    private String className = "";

    private int nId  = new Integer(0);

}

Copy the code

Actual call:

public class StudentTest {



    public static void main(String[] args) {

        Student student = new Student();



        student.setId(101);

        System.out.println(student.getId());

        student.setAme("hresh");

        student.setName("hresh");

        System.out.println(student);

    }

}

Copy the code

Note that there is a rule for naming attributes in the class that specifies a prefix + uppercase character, as in the above code if the attribute is name instead of name.

@SneakyThrows

Automatically throws checked exceptions without explicitly using a throws statement on a method

@SneakyThrows

public void read(a){

    InputStream inputStream = new FileInputStream("");

}

/ / equivalent to

public void read(a) throws FileNotFoundException {

    InputStream inputStream = new FileInputStream("");

}

Copy the code

@Builder

Use it on classes, constructors, and methods to provide you with the complex Builder APIs

@Builder

@Data

public class Student {

    private String name ;

    private int age;

}

Copy the code

Actual call:

public class StudentTest {



    public static void main(String[] args) {

        Student student = Student.builder().name("hresh").age(22).build();

    }

}

Copy the code

Is equivalent to:

public class Student {

    private String name;

    private int age;



    public String getName(a) {

        return name;

    }



    public void setName(String name) {

        this.name = name;

    }



    public int getAge(a) {

        return age;

    }



    public void setAge(int age) {

        this.age = age;

    }



    public static Builder builder(a){

        return new Builder();

    }

    public static class Builder{

        private String name;

        private int age;

        public Builder name(String name){

            this.name = name;

            return this;

        }



        public Builder age(int age){

            this.age = age;

            return this;

        }



        public Student build(a){

            Student student = new Student();

            student.setAge(age);

            student.setName(name);

            return student;

        }

    }

}

Copy the code