Record
type is a new feature introduced in java 16.
It already released as a preview feature in java 14.
java Record Type
Record Type
is specialized version and similar to a class.
Let’s see difference between Class
and Record Type
.
For example, you want to transfer Employee data between Service layer ,data and web layer, You need to write the boiler plate code for below things
- create a Employee class
- Write a Constructor class
- add private and public members
- provide setters and getters for members
- Also need to write a logic for duplicate records using
equals
,hashcode
andtoString
methods.
Here is an example
package java16;
import java.util.Objects;
public class Employee {
// member fields
private Long id;
private String name;
// Constructor
public Employee(Long id, String name) {
this.id = id;
this.name = name;
}
public static void main(String[] args) {
Employee emp = new Employee(1l, "John");
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Objects.equals(id, employee.id) && Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
return "Employee{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
With above code, You need to write a boilerplate code and need to provide constructor,setter/getter, tostring and hascode changes for each member variable.
Let’s see how to do the same with Record Type that eliminate above steps and simplified code process.
Here is an syntax
public record name(fields);
Here is an example
public record Employee(Long id,String name) {
}
// Parameter Constructor
public Employee(String id, String name) {
this.id = id;
this.name = name;
}
Let’s