Java Record

Records are immutable data classes that require only the type and name of fields. :

  • It is immutable in nature which leads to safer and more predictable code, particularly in multithreaded environments.
  • Provides compact syntax to create data class where in one line we can define record name, its fields and constructor:

   public record Student(String name, int division) {}        

  • The fields defined in a record are referred to as record components. The compiler generates accessors (getters) for these components, which are named the same as the fields. example: record.name()
  • Record provides a way to hold data without the need to write boilerplate code for constructors, getters, equals(), hashCode(), and toString() if is is needed. Java compiler automatically generates methods such as getters for each field, equals(), hashCode() and toString() when a record is defined.
  • Food for thought: Why it does not provide setters()?
  • We can define custom methods in record to encapsulate behaviour of the fields in record.

public record Student(String name, int division)                                                                       {                                                                                                                                            public String greet()                                                                                                              { return "Name of the student is " + name + " and is in division " + division; }.                  }        

  • We can serialize record like class. With libraries like Jackson or Gson , records work seamlessly without any extra configuration:

import com.fasterxml.jackson.databind.ObjectMapper;                                                                                        

ObjectMapper mapper = new ObjectMapper();                                                            String jsonString = mapper.writeValueAsString(new Student("Alice", 10));        

要查看或添加评论,请登录

社区洞察

其他会员也浏览了