Make writing a habit together! This is my first day to participate in the “Gold Digging Day New Plan · April More text challenge”, click to see the details of the activity.

Other important Lombok notes

Annotation @cleanup with @sneakythrows annotation

@ the Cleanup annotations

The @cleanup annotation generates code to close a resource without manually identifying and closing all resources through a try-catch-finally block

Create a new CleanupAnnotationTest under the Test package and test the @cleanup annotation

public class CleanupAnnotationTest {

    public void copyFile(String in, String out) throws Exception{
        @Cleanup FileInputStream fileInputStream = new FileInputStream(in);
        @Cleanup FileOutputStream fileOutputStream = new FileOutputStream(out);
        int r;
        while((r = fileInputStream.read()) ! = -1){ fileOutputStream.write(r); }}public static void main(String[] args) {}}Copy the code

The @cleanup annotation is used before the variable name of the resource that needs to be closed. Execute the main method to view the class file generated in the target directory

A try-catch-finally block is automatically generated to close the resource, preventing performance problems if the resource is not closed

@SneakyThrows

@ SneakyThrows: can to catch and throw, a. abnormalities can rewrite the above the main method is as follows: www.jianshu.com/p/7d0ed3aef…

www.cnblogs.com/acmaner/p/1…

The @sneakythrows method only applies to methods. The @Sneakythrows annotation replaces the manual exception throwing code in the program to capture and throw checked exceptions

New SneakyThrowsAnnotationTest test class, will be used by copyFile CleanupAnnotationTest code copy to SneakyThrowsAnnotationTest class

public class SneakyThrowsAnnotationTest {
    @Test
    @SneakyThrows
    public void copyFile(String in, String out){
        @Cleanup FileInputStream fileInputStream = new FileInputStream(in);
        @Cleanup FileOutputStream fileOutputStream = new FileOutputStream(out);

        int r;

        while((r = fileInputStream.read()) ! = -1){ fileOutputStream.write(r); }}}Copy the code

After adding the @sneakyannotation, there is no need to throw an exception on the method, and the program will not report an error

Can be determined according to the compiled class file, there are two layer try-catch SneakyThrowsAnnotationTest class, in the way that the outermost layer is added @ SneakyThrows exception handling code generated by the annotation. The inner try-catch-finally is the code that closes the resource

@ Accessors, annotations

The @accessor annotation is used to configure the result generated by getter/setter methods; An Accessor means an Accessor. The @accessor annotation contains three attributes fluent, chain, and prefix

Chain properties

Create a Porsche entity class under the Entity package. The chain property can be set to true or false

@Data
@Accessors(chain = true)
public class Porsche {

    private Integer id;
    private String name;
    private Double price;
    private Integer stock;
}
Copy the code

Run Maven’s complie command to view the compiled class file in the target directory

The @accessor (chain=true) annotation modifies the setter method generated by the @data annotation by changing the return value of the setter method from void to the entity class type, so that chain operations can be performed

Create a PorscheTest under the test package

public class PorscheTest {

    @Test
    public void testAccessorAnnotationChain(a){
        Porsche prosche = new Porsche();

        prosche.setId(1).setName("Taycan").setPrice(880000.00).setStock(110); System.out.println(prosche); }}Copy the code

When you set an object’s properties, you can do it with a single line of code; Execute test method

Fluent properties

Create a new Tesla entity class under the Entity package, and the Fluent property can be set to true or false

@Data
@Accessors(fluent = true)
public class Tesla {

    private Integer id;
    private String vehicleName;
    private String vehicleType;
    private String vehiclePrice;
    private String factory;
}
Copy the code

Run Maven’s compile command to view the class file of the compiled Tesla entity classes in the target directory

The @accessor annotation Fluent =true changes the getter/setter method name to the property name based on chain=true

Add TeslaTest test class under test package

public class TeslaTest {

    @Test
    public void testAccessorAnnotationFluent(a){
        Tesla tesla = new Tesla();
        tesla.id(1).vehicleName("Model S").vehicleType(The car run "").vehiclePrice("880000").factory(Shanghai Gigafactory); System.out.println(tesla); }}Copy the code

Compared with the setting of the chain=true attribute, Fluent =true unified the getter/setter method name. If the parameter is passed, it is equivalent to calling the setter method; if the parameter is not passed, it is equivalent to calling the getter method.

Execute test method

The prefix attribute

The prefix attribute removes the specified prefix representation and creates a new Jaugar entity class in the Entity package

@Data
@Accessors(prefix = "j")
public class Jaugar {

    private Integer jId;
    private String jName;
    private Double jPrice;
}
Copy the code

Click maven’s compile command to view the Jaguar Class file in the Target directory

The @accessors (prefix = “j”) annotation removes the specified prefix based on the getter/setter method generated by @data

Use of @slf4j logging annotations in Lombok

@slf4j can simplify logging in place of this code

private static final Logger logger = LoggerFactory.getLogger(Xxx.class);
Copy the code

In the figure above, slF4J and Commons-Loggin are logging specifications; Logback JDK-logging log4j log4j2 are logging implementations. If you want to achieve log unification, you need to use the bridge package. You can also refer to the solution provided by SLF4J official website

@ Slf4j annotations

Start by adding the relevant Jar package support

<! -- Log specification -->
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.7.36</version>
</dependency>

<! -- Log implementation -->
<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.2.11</version>
  <scope>test</scope>
</dependency>
Copy the code

Create a new LogAnnotationTest test class in the Test package, using the @SLf4J annotation

@Slf4j
public class LogAnnotationTest {
    
    @Test
    public void testLogger(a){
        log.error("This is the output log message."); }}Copy the code

Execute the testLogger method

View the compiled file

This automatically generates a constructor for us and defines a log property, which slF4J’s LoggerFactory returns by calling the getLogger method and output logs via the interface, which is also the preferred method

Create object with @Builder annotation and @singular annotation

@ Builder annotations

The @Builder annotation completely separates the creation and use of an object. The creation of an object can only be done with @Builder. After the object is created, it is immutable and can be used, but cannot be modified.

Create a new BuilderAnnotationTest test class under the Test package

@Builder
@Data
public class BuilderAnnotationTest {

    private static String staticField;

    private final String finalField;

    private final String initFinalField = "Initialized fields";

    private String field;

    public static void main(String[] args) {
        // Create the BuilderAnnotationTest object
        // First call the Builder method to create an object that can be chained
        BuilderAnnotationTest builderAnnotationTest = BuilderAnnotationTest.builder()
                                                      .finalField("Manual Assignment field finalField")
                                                      // Other attributes cannot be assigned
                                                      .field("Manually assign field")
                                                      // Create an object, which is immutable.build(); System.out.println(builderAnnotationTest); }}Copy the code

Execute main methodThe object can be successfully created following the console output instructions

View the compiled code in the target directory

The @Builder annotation helps us create a constructor

Defines a builder BuilderAnnotationTestBuilder inner class methods to create objects

The getter/setter/hashcode equals method are @ Data annotations

The @Builder annotation generates the inner class

This class contains two properties and an empty parameter constructor, several methods with attribute names that are used to assign values to properties, a toString method, and a build method that creates a BuilderAnnotationTest object using the two inner properties, Call the two-parameter constructor above BuilderAnnotationTest to create the object

The summary is to create an inner class to persist the attribute values of the attributes to be assigned, and use those attributes to create an immutable object by calling the constructor. The object creation process is invisible, so the object is immutable

To assign a value to a common property, call main again to see if the value of the common property of the created object changes

The initial values of common attributes are not carried when creating objects; Default values are not brought in unless manually assigned

@ the Singular annotations

Add a List attribute to BuilderAnnotationTest. @Singular simplifies operations by adding a List attribute to BuilderAnnotationTest

private List<String> listFields;
Copy the code

Modify the main method to manually assign the list attribute

public static void main(String[] args) {
    // Create the BuilderAnnotationTest object
    // First call the Builder method to create an object that can be chained
    BuilderAnnotationTest builderAnnotationTest = BuilderAnnotationTest.builder()
                                                  .finalField("Manual Assignment field finalField")
                                                  // Other attributes cannot be assigned
                                                  .field("Manually assign field")
                                                  .listFields(new ArrayList<>())
                                                  // Create an object, which is immutable
                                                  .build();
Copy the code

Execute main method

Add the @singular annotation to the list property

@Singular
private List<String> listFields;
Copy the code

Assign the list property manually againThere are two ways to assign

The @Singular annotation generates methods to append a single element individually, and consecutively, to a collection attribute. Perform the test

The listField method assignment succeeded. You can also call listField consecutively to assign multiple elements to a listPerform the testThis indicates that successive calls to assign are also successful

View the generated class code in the target directory

The listField method can take a single String argument and add it to the listFields initializer. This helps us solve the problem of how to fill in the first element when the collection is empty

A clearListFields method is also generated to clear the collection when it is not empty

If the set is empty, an empty list is created and assigned to the list. If there is only one element, a singletonList is created and assigned to the list. Finally, an immutable set is created and assigned to the list