java - 将值设置为 Java 15 记录中的属性之一
问题描述
我在我的代码中使用 Java 15 预览功能记录,并将记录定义如下
public record ProductViewModel
(
String id,
String name,
String description,
float price
) {
}
在控制器级别,我有以下代码
@Put(uri = "/{id}")
public Maybe<HttpResponse> Update(ProductViewModel model, String id) {
LOG.info(String.format("Controller --> Updating the specified product"));
return iProductManager.Update(id, model).flatMap(item -> {
if(item == null)
return Maybe.just(HttpResponse.notFound());
else
return Maybe.just(HttpResponse.accepted());
});
}
在模型中的 UI 中,没有传递id的值,但是,它作为路由参数传递。现在我想在控制器级别设置值,例如
model.setid(id) // Old style
如何将值设置为记录特定属性
解决方案
你不能。记录属性是不可变的。但是,您可以做的是添加一个 wither 以创建具有相同属性但新 id 的新记录:
public record ProductViewModel(String id,
String name,
String description,
float price) {
public ProductViewModel withId(String id) {
return new ProductViewModel(id, name(), description(), price());
}
}
推荐阅读
- spring-boot - JPA - 当两个外键是实体的主键时,OneToOne 关系出现问题
- node.js - 如何将每个乘以作为快速车把(#each)?
- gradle - Gradle 和 webpack --watch
- syndesis - How to install syndesis (stable) on minishift
- c# - 我可以在 Web Api 的驼峰格式格式中使用 Post 请求数据(我的意思是 json 正文)吗?
- java - selenium no such session excpetion: session
IEDriverServer 中不存在 - javascript - 检查模型/会话是否存在并且在 JavaScript 中不为空
- bash - Imagemagick - 如何创建适合任何图像大小的注释?
- mysql - 当我尝试激活我的代码 navicat 12 时出错
- c# - 谷歌云语音命令