[Java] About Records added in preview in Java JDK 14

1 minute read

Introduction

Java is also fast and JDK15 will be released soon! (Scheduled for September 2020) However, it was honest that the JDK 14 just before that didn’t catch up much… I went through a lot of research and learned that the concept of Records was released as a preview version in JDK14, so I wrote a little article.

*Because it is a Preview version, the shape may change again after JDK15. Please note.

What is # Records It is below. https://openjdk.java.net/jeps/359 Record is now available for data storage, As a result, the class to which this is added becomes an immutable object. Specifically, it has the following form.

record Point(int x, int y) {}

The above results in the following classes.

class Point extends Record {
  private final int x;
  private final int y;

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

  public int x() {
    return x;
  }
  public int y() {
    return y;
  }

  public int hashCode() {...}
  public boolean equals() {...}
  public String toString() {...}
}

As above, the field variable cannot be accessed from other than the constructor (immutable), equals hashCode A class that implements the toString method is generated.

It seems that the value of the argument can be checked as follows.

record Point(int x, int y) {
  public Range {
    // When only values less than x can be set in y
    if (x> y) throw IllegalArgumentException();
    // It will set the value without explicitly setting it as follows.
    // this.x = x;
    // this.y = y;
  }
}

Remarks

It’s still a preview version, so it’s unclear what it will be like in the future, but I thought it could be intuitively understood by using it in DTO or using Record. Personally, the expression that it is a named tuple was the most comfortable. For those who want to know more, the following articles were very easy to understand. https://www.infoq.com/jp/articles/java-14-feature-spotlight/

Java will continue to evolve… I will catch up properly. Thank you for reading!

Tags:

Updated: