public class SampleRecord {
private final String name;
private final int age;
private final String address;
public Reee(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Reee reee = (Reee) o;
return age == reee.age && Objects.equals(name, reee.name) && Objects.equals(address, reee.address);
}
@Override
public int hashCode() {
return Objects.hash(name, age, address);
}
@Override
public String toString() {
return "Reee{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
public record SampleRecord(
String name,
int age,
String address
) {}
Record는 모든 필드를 매개변수로 가지는 생성자를 기본적으로 제공한다. 기본 제공 생성자가 하지 못하는 데이터 검증이나, 일부의 값만 전달받는 생성자를 만드는 것도 가능하다. 이러한 생성자를 컴팩트 생성자라고 한다.
public record SampleRecord(
String name,
int age,
String address
) {
public SampleRecord {
if (age < 0) throw new IllegalArgumentException("Age cannot be negative");
}
}
public record SampleRecord(
String name,
int age,
String address
) {
public SampleRecord(String name, int age) {
this(name, age, "Unknown Address");
}
}
레코드는 static field와 method를 가질 수 있다.
public record SampleRecord(
String name,
int age,
String address
) {
// static field
public static String UNKNOWN_ADDRESS = "Unknown Address";
public SampleRecord(String name, int age) {
this(name, age, UNKNOWN_ADDRESS);
}
// static method
public static SampleRecord unnamed(int age, String address) {
return new SampleRecord("Unnamed", age, address);
}
}
SampleRecord.unnamed(20, "Seoul");
String unknownAddress = SampleRecord.UNKNOWN_ADDRESS;
References
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Record.html
https://medium.com/javarevisited/java-records-when-why-to-use-them-ebd48de637b6
https://colevelup.tistory.com/28
https://www.baeldung.com/java-record-keyword
https://scshim.tistory.com/372