1. The birth background of Record
Java's Record (record class) is a preview feature introduced by Java 14 and is officially standardized in Java 16. The original design intention is to simplify the definition of immutable data classes and solve the problem of a large number of boilerplate codes in traditional POJO classes (such as constructors, getters, equals, hashCode, toString, etc.). For example, a simplePerson
Classes require 30+ lines of code in traditional writing, while Record only requires one line.
Traditional class vs Record class:
// Traditional POJO (30+ lines)public class Person { private final int id; private final String name; // Constructor, getter, equals, hashCode, toString...} // Record equivalent implementation (1 line)public record Person(int id, String name) {}
Record allows developers to focus on the data itself rather than duplicate template code.
2. The core features of Record
-
Immutability
- All fields in Record are by default
final
, it cannot be modified after creation, and it is naturally thread-safe. - Suitable for scenarios such as DTO and configuration items that require data consistency.
- All fields in Record are by default
-
Automatic generation method
- The compiler automatically generates the following methods:
- Full ginseng constructor
- Field accessors (such as
id()
、name()
, notgetId()
) -
equals()
、hashCode()
、toString()
。
- The compiler automatically generates the following methods:
-
Concise syntax
- use
record
Keyword definition, compact syntax:public record Point(int x, int y) {}
- use
-
Restrictive design
- The Record class is implicit
final
, cannot be inherited. - Non-static instance fields cannot be declared (only fields are allowed to be defined by the parameter list).
- The Record class is implicit
3. Basic usage of Record
1. Definition and Instantiation
public record User(String username, String email) {} // InstantiationUser user = new User("Alice", "alice@"); (()); // Output "Alice"
2. Custom method
Record allows adding custom methods:
public record Circle(double radius) { // Calculate area public double area() { return * radius * radius; } }
3. Parameter verification (compact constructor)
Field verification is achieved through a compact constructor:
public record Email(String address) { public Email { if (!("@")) { throw new IllegalArgumentException("Invalid email"); } } }
4. Implement interfaces and generics
Record can implement interfaces and support generics:
public record Pair<T, U>(T first, U second) implements Serializable { public String toJson() { return "{ \"first\": \"" + first + "\", \"second\": \"" + second + "\" }"; } }
4. Advanced application of Record
-
Replace DTO/VO
- Quickly define API response models:
public record ApiResponse<T>(int code, String message, T data) {}
- Quickly define API response models:
-
Pattern Matching (Java 17+)
- Combined
instanceof
Deconstruct data:Object obj = new Point(3, 4); if (obj instanceof Point(int x, int y)) { ("coordinate: (" + x + ", " + y + ")"); }
- Combined
-
Database Mapping
- Simplify JDBC result set processing:
try (ResultSet rs = ()) { return new User(("id"), ("name")); }
- Simplify JDBC result set processing:
-
Functional programming
- As a lightweight tuple (e.g.
Pair
、Triple
):record Pair<A, B>(A first, B second) {} List<Pair<String, Integer>> pairs = (new Pair<>("Java", 1995));
- As a lightweight tuple (e.g.
5. Comparison between Record and Lombok
characteristic | Record | Lombok |
---|---|---|
Immutability | Default support | Need to be added manuallyfinal
|
Code generation | Language native support | Depend on annotation processor |
Pattern matching | Fully compatible | Not supported |
compatibility | Requires JDK 16+ | Compatible with old versions |
Variability | Immutable | Supports variable classes (such as@Data ) |
Select suggestions:
- Priority Record: Requires immutable classes, use pattern matching, or JDK 16+ environment.
- Select Lombok: Mutable classes or compatible with old code.
6. Things to note
-
Uninheritability
- Record cannot inherit other classes (implicit inheritance
)。
- Record cannot inherit other classes (implicit inheritance
-
Field Limitations
- All fields must be declared through parameter lists and dynamic addition of instance fields is not supported.
-
Serialization
- Need to be explicitly implemented
Serializable
Interface.
- Need to be explicitly implemented
-
Framework compatibility
- Some frameworks (such as older Spring) may need to be adapted to the Record type.
7. Future Outlook
- Pattern matching enhancement: with
sealed class
Combined, build a stricter type system. - Framework integration: Frameworks such as Spring or support Record as data carrier by default.
- Functional extension: In-depth combination with Stream and Optional to improve code expression.
Summarize
Java Record significantly reduces boilerplate code of data classes through minimalist syntax and immutability, while improving code security and maintainability. It is suitable for DTO, pattern matching, functional programming and other scenarios.
This is the end of this article about Java Record implementation examples. For more related Java Record content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!