导语:JDK17的record
特性让数据类开发变得高效简洁。本文将结合真实开发场景,通过基础到高级的案例,手把手教你玩转record
!
一、初识Record:简化数据载体类
1.1 传统POJO痛点
传统数据类需要手写构造函数、getter、equals等方法,代码冗余度高:
public class User {
private Long id;
private String username;
// 省略10+行样板代码...
}
1.2 Record基础写法
同样功能用record
仅需1行:
public record UserRecord(Long id, String username) {}
自动生成:
-
全字段构造
-
public访问方法(
id()
/username()
) -
equals/hashCode
-
toString
二、初级应用:常见开发场景
2.1 DTO数据传输
接口返回数据时推荐使用:
// 用户查询接口
public UserDTO getUserInfo(Long userId) {
User user = userRepository.findById(userId);
return new UserDTO(user.getId(), user.getName());
}
// 使用record定义DTO
public record UserDTO(Long id, String name) {}
2.2 配置参数封装
系统配置项天然适合不可变特性:
public record RedisConfig(String host, int port, String password) {}
// 配置初始化
RedisConfig config = new RedisConfig("127.0.0.1", 6379, "pass123");
System.out.println("Redis端口:" + config.port());
三、高级应用:复杂场景实战
3.1 嵌套结构处理
处理多层JSON数据时优势明显:
public record OrderResponse(
Long orderId,
List<LineItem> items,
Address address
) {
// 嵌套record定义
public record LineItem(String sku, int quantity) {}
public record Address(String city, String detail) {}
}
// 使用示例
OrderResponse response = new OrderResponse(
1001L,
List.of(new LineItem("A001", 2)),
new Address("北京", "朝阳区XXX街道")
);
3.2 模式匹配(JDK17新特性)
结合switch表达式处理不同类型消息:
public interface Message {}
public record TextMessage(String content) implements Message {}
public record ImageMessage(String url, int size) implements Message {}
// 消息处理器
public void processMessage(Message msg) {
switch(msg) {
case TextMessage t -> System.out.println("文字内容:" + t.content());
case ImageMessage i -> System.out.println("图片大小:" + i.size());
default -> throw new IllegalArgumentException();
}
}
3.3 数据验证技巧
通过紧凑构造函数添加校验:
public record ValidatedUser(String username, String email) {
public ValidatedUser {
if (username == null || username.isBlank()) {
throw new IllegalArgumentException("用户名不能为空");
}
if (!email.contains("@")) {
throw new IllegalArgumentException("邮箱格式错误");
}
}
}
// 测试非法参数
ValidatedUser user = new ValidatedUser("", "invalid"); // 抛出异常
四、特别注意事项
-
不可变性陷阱:record字段final修饰,修改字段需新建对象
UserRecord user = new UserRecord(1L, "admin"); UserRecord newUser = new UserRecord(user.id(), "newName");
-
JPA实体慎用:Hibernate等ORM框架对record支持尚不完善,推荐用于DTO/ViewObject
3. JSON序列化:Jackson 2.12+完美支持record序列化
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
五、开发实践建议
-
✅ 适用于:API返回值、配置参数、临时数据载体
-
❌ 不适用于:需要继承的类、可变数据实体
总结:合理运用record可以使代码简洁性提升50%以上!在微服务、配置管理等场景中尤其高效。你还在手写getter/setter吗?快来体验record的魔力吧!
讨论:你在项目中是如何使用record的?欢迎留言分享实战经验!如果本文对你有帮助,请点赞收藏支持~