Mastodon

Java 14 Records

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

public record Person(
        String name,
        Integer age
) {
 
    // Definition of additional attributes not allowed in records:
//    private Integer x;
 
    // Definition of static fields allowed:
    private static Integer MY_NUMBER = 42;
 
    /**
     * Constructor with mandatory attribute.
     *
     * @param name  mandatory name
     */
    public Person(String name) {
        this(name, null);
    }
 
    // Definition of additional methods allowed:
    public String saySomething() {
        return name + " is " + age + " years old";
    }
}
import org.junit.jupiter.api.Test;
 
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
 
public class RecordTest {
 
    @Test
    void recordTest() {
 
        Person steven = new Person("Steven", 36);
 
        // No usual getter-syntax, instead just method with name of attribute:
        assertEquals("Steven", steven.name());
 
        // Records are immutable:
//        steven.setName();
 
        // Optional constructor with mandatory attributes:
        Person justSteven = new Person("just Steven");
        assertNull(justSteven.age());
 
        // Calling additional method:
        System.out.println(steven.saySomething());
    }
}

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..