我在我的代码中使用 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/