Java 14 released, you can throw away the Lombok?

2020 March 17 release, Java officially released JDK 14, available now available for download. In JDK 14, a total of 16 new features, this paper to introduce a feature which: JEP 359: Records

Official Tucao most deadly

As early as February 2019, Java Language Architect Brian Goetz, wrote an article ( cr.openjdk.java.net/~briangoetz... ), a detailed description of the Java language and Tucao, he and many programmers complained that "Java is too long-winded," or there is too much "red tape", he mentioned: developers want to create a data-carrier type (plain data carriers) usually have to write a lot of low-value, repetitive, error-prone code. Such as: constructors, getter / setter, equals () , hashCode () and toString () and the like.

That many people choose to use the IDE function to automatically generate code. Some developers choose to use some third-party libraries, such as Lombok and so on to generate these methods, which will lead to a performance (surprising behavior) and surprisingly poor debuggability (poor debuggability).

So, what pure data carrier Brian Goetz great God is mentioned in the end means it. He cited a simple example:

final class Point {
    public final int x;
    public final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // state-based implementations of equals, hashCode, toString
    // nothing else
}复制代码

There is actually a pure Piont data carrier, he represents a "point" included in the x and y coordinates, and provides only a constructor, and some equals, hashCode like.

So, BrianGoetz Great God put forward an idea, he mentioned, Java can represent pure data carrier for this another way.

In fact, in other object-oriented languages, have long been defined for such separate pure data carrier, such as in Scala case, Kotlin C # and the data in the record. These definitions, although on different semantics, but they have in common is a part or all of the state class in the class may be directly described in the header, and the class includes only the pure data only.

So he proposed Java is not pure can also define a data carrier by way of it?

record Point(int x, int y) { }复制代码

God said to use record, so there

Like the great God Tucao it, we usually need to write a lot of code to make it useful class. Such as the following:

  • toString () method
  • hashCode() and equals()方法
  • Getter Methods
  • There are a constructor

For this simple class, these methods are generally boring, repetitive, and can be easily produced mechanically kind of thing (IDE typically provide this function).

When you read someone else's code, it may be more headaches. For example, someone else might he wrote to it? If you add in the reconstruction process using hashCode () and equals () IDE generated to handle all the fields and the like, but how can we determine in the case of each row does not check the implementation field without re-generation method, what would happen?

Great God Brian Goetz proposed the idea to use the definition of a pure record data carrier, then, Java will be 14 includes a new feature: EP 359: Records, is the author Brian Goetz

Records goal is to extend the Java language syntax, Records provides a compact syntax for declaring class for the creation of a class is "field, but the field, in addition to field nothing" category. By doing this kind of statement, the compiler can automatically create all the methods and methods so that all the fields involved hashCode () and so on. This is a preview feature in JDK 14.

Yiyanbuge decompile

Records usage is relatively simple, and custom Java classes as:

record Person (String firstName, String lastName) {}复制代码

As above, we define a Person record, which comprises two components: firstName and lastName, and an empty class thereof.

So, this thing looks like it's a syntactic sugar, he in the end is how to achieve that?

Let him try to compile, remember to use --enable-previewparameters because records feature is currently in JDK 14 or a preview (preview) function.

> javac --enable-preview --release 14 Person.java
Note: Person.java uses preview language features.
Note: Recompile with -Xlint:preview for details.复制代码

As described above, Record just a class, and its purpose is to save public data. Let's look at decompile with javap, will get the following code:

public final class Person extends java.lang.Record {  
  private final String firstName;
  private final String lastName;
  public Person(java.lang.String, java.lang.String);
  public java.lang.String toString();
  public final int hashCode();
  public final boolean equals(java.lang.Object);
  public java.lang.String firstName();
  public java.lang.String lastName();
 }复制代码

Decompile derived class, we can get the following information:

1, generates a final Person class type (class), the class described can not have the subclass.

2, this class inherits java.lang.Record class, which we use to create out of the enum enumerations are somewhat similar to the default inheritance java.lang.Enum

3, there are two class types of private final properties. Therefore, the record attribute class should be defined private final type.

4, there is a public constructor, the reference is to the two main attributes. If you look at the method by which the bytecode body, then its content is the following code, you must be familiar with:

public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}复制代码

5, there are two getter method, named firstName and lastName. This naming JavaBean defined differently, perhaps this way the great God wanted to tell us define the record is not out of a JavaBean it.

6, also help us to automatically generate a toString (), hashCode () and equals () method. It is worth mentioning that this method relies invokedynamic three suitable methods to implicitly implement comprises a dynamic call.

You can also play this

The previous example, we simply create a record, then, record but also in other member variables and methods do? We look at.

1, we can not add instance in the field to record. However, we can add static fields.

record Person (String firstName, String lastName) {
    static int x;
}复制代码

2, we can define the static and instance method, the state of the operation target.

record Person (String firstName, String lastName) {
    static int x;

    public static void doX(){
        x++;
    }

    public String getFullName(){
        return firstName + " " + lastName;
    }
}复制代码

3, we can also add a constructor.

record Person (String firstName, String lastName) {
    static int x;

    public Person{
        if(firstName == null){
            throw new IllegalArgumentException( "firstName can not be null !"); 
        }
    }

    public Person(String fullName){
        this(fullName.split(" ")[0],this(fullName.split(" ")[1])
    }
}复制代码

So, we can add static fields / methods in the record, but the question is, should we do this?

Remember, record goal behind the launch is to enable developers to related fields as a single immutable data items together without the need to write lengthy code. This means that whenever you want to add more fields / methods to your records, consider whether it should use the full class instead.

to sum up

record address the use of class A common problem as a data wrapper. Pure Class significantly simplifies the data from the few lines of code for the line of code.

However, record the current language is a preview feature, which means that, although it has been fully realized, but has not been standardized in the JDK.

So the question is, then if you were using Java 14, Lombok you will use it? Oh no, you may not have access short period of time, because you probably have not use the familiar Java 8 ~

References:

openjdk.java.net/jeps/359

dzone.com/articles/a-…

aboullaite.me/java-14-rec…

cr.openjdk.java.net/~briangoetz…

About the Author: Hollis, a quest for Coding has a unique person, an Internet company technical experts, personal technology blogger, technical articles, the amount of reading the whole network of tens of millions, "three classes programmer" joint author.

Guess you like

Origin juejin.im/post/5e7421b8518825497468178a