Java RecordsDecember 27, 2022
Java Record is a new way to declare a class to pass immutable data. Records were first introduced in Java 14 but they become more common within Java 15. So where they are used and what are their advantages?
Before Java records, a class should be created with boilerplate fields and methods in order to pass immutable data between objects. With record keyword, these boilerplate fields and methods are discarded and all are done with just a declaration.
So, what you can do with a record object;
- One common public constructor with all properties in the record is automatically generated
- All properties in the record are marked as private final automatically
- Getter methods for all properties are automatically created
- toString, hashCode, equals methods are created automatically
- Properties can be decorated with annotations like validity check annotations
But you cannot extend other classes within a record object.
Now, let’s go over a code examples to deep dive in record functionality in java. Within the code, you can see the difference between an old school way of declaring a class, declaring a class with Lombok library and declaring the same class with record keyword.
Old School Class Declaration
Let’s start with old school way to declare a class to model a simple enterprise example.
Please check the Gist to see the old school way to declare a class in Java.
As you can see from the code snippet, you need to;
- Define constructor method
- Define getter methods for all properties
- Define toString, hashCode, equals methods
All definitions are done 50 lines of code.
Class Declaration with Lombok
Now, let’s move to define the same class with using Lombok library.
Please check the Gist to see the way to declare a class with Lombok library in Java.
It takes less lines of code to declare the same enterprise class by using Lombok. You need to add Lombok dependency to your code base in order to declare the class in this way.
Class Declaration with Java Record
Now, let’s declare the same enterprise class by using Java Record.
Please check the Gist to see the way to declare a class with Java Record.
You just need to give your class name and its properties to declare a class with Java Record. You will use the native Java language functionalities to define your;
- public constructor with all properties
- all private final properties
- getter methods for all properties
- toString, hashCode, equals methods
- annotations to decorate your class
Java does all these for you. Just decide your class name & its properties.
To Sum Up
Long story short, I try to explain Java record which were introduced within Java 14 and then become more common within Java 15.
I try to explain the usage of Java record with a full project structure including controller, mapper, service, DTO, entity, repository implementations.
Example source code can be found within java-record-example repository.
Your comments & questions are always welcomed :)