Record Classes
Java record Classes (introduced first in Java 14) helps writing less boiler plate codes and maintain objects which are immutable by design.
In Java, a record is a special type of class declaration aimed at reducing the boilerplate code. Java records were introduced with the intention to be used as a fast way to create data carrier classes, i.e. the classes whose objective is to simply contain data and carry it between modules, also known as POJOs (Plain Old Java Objects) and DTOs (Data Transfer Objects). Record was introduced in Java SE 14 as a preview feature.
Let us first see a simple Record and equivalent class.
public record AuthTokenRecord(String token, LocalDateTime dateExpiary) {
public AuthTokenRecord {
if (token == "" || token == null)
throw new java.lang.IllegalArgumentException(String.format("Invalid token: %f", token));
}
}
The above record is equivalent to the following class definition.
public final class AuthTokenClass {
private final String token;
private final LocalDateTime dateExpiary;
private final LocalDateTime dateCreated;
public AuthTokenClass(String token, LocalDateTime dateExpiary, LocalDateTime dateCreated, LocalDateTime date2) {
this.token = token;
this.dateExpiary = date2;
this.dateCreated = dateCreated;
}
public String getToken() {
return token;
}
public LocalDateTime getDateExpiary() {
return dateExpiary;
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
}
Record automatically generates the followings
- A public constructor
- getters,
- toString hashcode and equals methods
Restrictions on Records
- Records cannot extend any class
- Records cannot declare instance fields (other than the private final fields that correspond to the components of the record component list); any other declared fields must be static
- Records cannot be abstract; they are implicitly final
- The components of a record are implicitly final
When should we use Records or JavaBeans
The primary use case of the record is to hold immutable data. For example if we want to create immutable objects like Currency(code,name) or AuthToken(token,expiary) etc that once created will not be changed. Benefits for developers is writing less code and making sure the data is properly encapsulated.
Comments
Post a Comment