gpt4 book ai didi

java - 将值设置为 Java 15 记录中的属性之一

转载 作者:行者123 更新时间:2023-12-03 15:15:35 24 4
gpt4 key购买 nike

我在我的代码中使用 Java 15 预览功能记录,并将记录定义如下

public record ProductViewModel
(
String id,
String name,
String description,
float price
) {
}
在 Controller 级别我有以下代码
@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 没有传递,但是,它作为路由参数传递。现在我想在 Controller 级别设置值,例如
model.setid(id) // Old style
如何将值设置为记录特定属性

最佳答案

你不能。记录属性是不可变的。但是,您可以做的是添加一个凋零来创建一个具有相同属性但新 id 的新记录:

public record ProductViewModel(String id,
String name,
String description,
float price) {

public ProductViewModel withId(String id) {
return new ProductViewModel(id, name(), description(), price());
}
}

关于java - 将值设置为 Java 15 记录中的属性之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65253856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com