Java 14: Records


Posted by Steven

This is just a small code snippet demonstrating the preview of the new Records in Java 14. 

  1. public record Person(
  2. String name,
  3. Integer age
  4. ) {
  5.  
  6. // Definition of additional attributes not allowed in records:
  7. // private Integer x;
  8.  
  9. // Definition of static fields allowed:
  10. private static Integer MY_NUMBER = 42;
  11.  
  12. /**
  13.   * Constructor with mandatory attribute.
  14.   *
  15.   * @param name mandatory name
  16.   */
  17. public Person(String name) {
  18. this(name, null);
  19. }
  20.  
  21. // Definition of additional methods allowed:
  22. public String saySomething() {
  23. return name + " is " + age + " years old";
  24. }
  25. }
  1. import org.junit.jupiter.api.Test;
  2.  
  3. import static org.junit.jupiter.api.Assertions.assertEquals;
  4. import static org.junit.jupiter.api.Assertions.assertNull;
  5.  
  6. public class RecordTest {
  7.  
  8. @Test
  9. void recordTest() {
  10.  
  11. Person steven = new Person("Steven", 36);
  12.  
  13. // No usual getter-syntax, instead just method with name of attribute:
  14. assertEquals("Steven", steven.name());
  15.  
  16. // Records are immutable:
  17. // steven.setName();
  18.  
  19. // Optional constructor with mandatory attributes:
  20. Person justSteven = new Person("just Steven");
  21. assertNull(justSteven.age());
  22.  
  23. // Calling additional method:
  24. System.out.println(steven.saySomething());
  25. }
  26. }

Once published as a non-preview feature, Records will save us a lot of boilerplate-code.

Update: A Java Record is not suitable to be used as a JPA or Hibernate entity..

Share: