Are you still write Java code set / get method? Do not tell me you have not used Lombok

Foreword

what? Your Java code is also filled with a lot of set / get method?

We are beginning to learn the Java language spoken, object-oriented features is the three encapsulation, inheritance, and polymorphism. In Java, to ensure that the packaging, it is necessary to privatize the member variables, provide external set / get methods to access, although the IDE, like the eclipse, IDEA provides shortcuts to generate a set / get method, but in doing project, a JavaBean often have a lot of member variables, a variable corresponding to the two methods, if there are 10 member variables, then the method will correspond to more than 20, and perhaps to write a constructor, equals methods, and require maintenance. As a result, the code will become very redundant, these seem very long without much technical content, once modify the properties, it is easy to forget to change the appearance of the corresponding method mistakes.

I was watching Gangster source project and see their code did not set / get methods, replaced by a mark on the JavaBean comment, I am very curious, in fact they are using a technique called Lombok plug-in, then go to learn more about this plugin.

Lombok Background

The official described 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.

Roughly meaning Lombok by increasing the number of "handlers" can make Java is simple and fast.

Lombok Use

Annotations can Lombok manner, at compile time automatically generated constructor property, getter / setter, equals, hashcode, toString method. Appears that there is no magic getter and setter methods in the source code, but there are getter and setter methods in the compiled byte code file. This eliminates the need to manually rebuild the trouble code, making the code look more succinctly.

Lombok is used with reference to jar packages, you can at the official website (https://projectlombok.org/download) download jar package can also be used to add a dependency maven:

<dependency>
  <groupId>org.projectlombok</groupId>

    <artifactId>lombok</artifactId>

    <version>1.18.10</version>

    <scope>provided</scope>

</dependency>

 

note:

The first time you use the plug-ins need to do the following steps Lombok configuration

  • The plug-in installation to Lombok IDEA
file -> setting

Select Plugins, search Lombok, click Install

  • Select the default compilation mode is javac, because the eclipse is not supported by way of Lombok compilation, javac compiler support Lombok way.
  • Open the annotation builder Enable annotation processing

Note again:

IntelliJ IDEA 2019.2 (that is, I use the version) is not supported by default Lombok widget needs to go

https://plugins.jetbrains.com/plugin/6317-lombok/versions

Download the corresponding version of the plug, then manually introduced, select File in the IDEA -> Setting -> plugins find Install Plugin from Disk ... (different locations may be different note version)

Next, we analyze the specific use of annotations in Lombok

@Data

@Data annotation on the class, setter / getter, equals, canEqual, hashCode, toString method automatically generates classes for all properties, such as the final attribute, no attribute setter method for the generation.

For example, we write a class students

@Data
public class Student {

    private String name;

    private Integer age;

    private Integer id;

    private String major;

}

So that you can call the set / get the method.

@Getter/@Setter

If you think @Data too cruel (because @Data collection @ ToString, @ EqualsAndHashCode, @ Getter / @ Setter, all the features @ RequiredArgsConstructor of) the fine is not enough, you can use @ Getter / @ Setter annotation, this annotation on the property, you can generated automatically set / get the corresponding method attribute.

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");

    }
}

 

@NonNull

The annotation used on a property or constructor, Lombok is non-empty generates a statement can be used to verify the parameters, can help prevent a null pointer.

public class Student {
  @Setter private String name;

    private Integer age;

    private Integer id;

    private String major;

    

    public Student(@NonNull String name) {

        this.name = name;

    }

}

 

@Cleanup

The notes can help us to automatically call close () method, greatly simplifies 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);

    	}

  	}

}

 

@EqualsAndHashCode

By default, will use all non-static (non-static) and non-transient (non-transient) and equals the hashCode generating property, you can also exclude annotation to exclude some properties.

@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

Use @ToString annotation class, generates a Lombok is toString () method, by default, will output class names, all attributes (attribute defines the order will follow), divided by a comma.

By includeFieldNames parameter set to true, you can clear the output of toString () property. This is a bit convoluted, look through the code will be more clearly some.

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

        }

    }

}

@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor

No argument constructor, some parameters configured, full-argument constructor. Lombok not achieve more argument constructor overload.

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

    }

}
Published 239 original articles · won praise 48 · views 30000 +

Guess you like

Origin blog.csdn.net/Sqdmn/article/details/105017441