CTO: don't write the set/get method in Java code. Catch a fine

preface what? Is your Java code still full of set/get met...

preface

what? Is your Java code still full of set/get methods?

When we first started to learn the Java language, we said that the three characteristics of object-oriented are encapsulation, inheritance, and polymorphism. In Java, to ensure encapsulation, you need to privatize member variables and provide set/get methods for external access. Although the current ides, such as eclipse and IDEA, provide shortcut keys to generate set/get methods, when you are working on a project, a JavaBean is needed There are often many member variables. One variable corresponds to two methods. If there are more than 10 member variables, there will be more than 20 methods. You may also need to write constructor, equals and other methods, which need to be maintained. In this way, the code will become very redundant, which is very lengthy and not too technical. Once the property is modified, it is easy to forget to modify the corresponding method.

When I look at the source code of big guy's project, I see that there is no set/get method in their code. Instead, they annotate JavaBean s. I'm very curious. They used a plug-in called Lombok, so I went to learn about this plug-in in in detail.

Lombok background

The official introduction is 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.

Lombok can make Java simple and fast by adding some "handlers".

How to use Lombok

Lombok can automatically generate constructor, getter/setter, equals, hashcode and toString methods for properties during compilation through annotation. The magic is that there are no getter and setter methods in the source code, but there are getter and setter methods in the bytecode file generated by compilation. This saves the trouble of manually rebuilding the code and makes the code look more concise.

Lombok can be used in the official website just like jar package( https://projectlombok.org/download )Download jar package, you can also use maven to add dependencies:

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

be careful: The first time you use the Lombok plug-in, you need to configure it as follows

  • Install Lombok plug-in to IDEA file -> setting Select Plugins, search Lombok, and click Install
  • Choose javac as the default compilation mode, because eclipse does not support Lombok compilation mode, and javac supports Lombok compilation mode.
  • Open annotation generator Enable annotation processing

Again: IntelliJ IDEA 2019.2 (that is, my version) does not support Lombok plug-in by default. You need to go to https://plugins.jetbrains.com/plugin/6317-lombok/versions Download the plug-in of the corresponding version, and then import it manually. Select File - > setting - > plugins in IDEA to find Install Plugin from Disk (note that different versions may be different)

Let's analyze the specific usage of annotations in Lombok

@Data @Data Annotation on a class, it will automatically generate setter/getter, equals, canEqual, hashCode, toString methods for all properties of the class. If it is a final property, it will not generate setter methods for that property. Let's write a student class

@Data public class Student { private String name; private Integer age; private Integer id; private String major; }

In this way, you can call the set/get method.

@Getter/@Setter If you think @Data Too brutal (because @ Data sets all the features of @ ToString, @ EqualsAndHashCode, @ Getter/@Setter, @ RequiredArgsConstructor) is not fine enough. You can use the @ Getter/@Setter annotation, which can automatically generate the set/get method for the corresponding attribute on the 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 When the annotation is used on a property or constructor, Lombok will generate a non null declaration, which can be used to verify parameters and help avoid null pointers.

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 This annotation can help us call the close() method automatically, which 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, all non static and non transient attributes are used to generate equals and hashCode, and some attributes can be excluded through 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 Class uses @ ToString annotation. Lombok will generate a toString() method. By default, it will output the class name, all properties (in the order of property definition), and use commas to separate them. By setting the includeFieldNames parameter to true, you can explicitly output the toString() attribute. Is this a bit of a detour? It will be clearer through the code.

@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 Parameterless constructor, partial parameter constructor, full parameter constructor. 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; } }

Source: Mr.ml

Welcome to my WeChat official account, "code breakout", sharing technologies like Python, Java, big data, machine learning, AI, etc., focusing on code farm technology upgrading, workplace breakout and mental transition, and 200 thousand + code growth, the first stop to grow with you.

29 May 2020, 11:15 | Views: 7980

Add new comment

For adding a comment, please log in
or create account

0 comments