3

What are Java Records?

 1 year ago
source link: https://xebia.com/blog/what-are-java-records/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Blog

What are Java Records?

18 Nov, 2022
header-wave.svg
Share

Records in Java (3 part series)

  1. What are Java Records?
  2. How to use Java Records
  3. Java Records as Data Transfer Objects (upcoming)

Records have been in Java since version 16, but what are they and what can you use them for?

Records can be thought of as a replacement for simple data-holding POJOs.
These holders usually have one or more of the following properties:

  • They are defined solely by the data they hold
  • They have an equals() and hashCode() method based solely on their data
  • Their fields are private and final, and they define a getter method for them
  • They are written to and read from another format, like JSON or the database

Here is an example of such a POJO:

final class Customer {
  private final UUID id;
  private final String name;

  public Customer(UUID id, String name) {
    this.id = id;
    this.name = name;
  }

  public UUID getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  @Override
  public String toString() {
    return "Customer[id=" + id + ", name=" + name + "]";
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Customer customer = (Customer) o;
    return id.equals(customer.id) && name.equals(customer.name);
  }

  @Override
  public int hashCode() {
    return Objects.hash(id, name);
  }
}

Now let’s see the equivalent record implementation:

record Customer(String id, String name) {}

Need we say more? You can now stop reading and start using records everywhere,
or you can continue on to Part 2: how you use Java Records.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK