首页 > 解决方案 > 将值设置为 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

如何将值设置为记录特定属性

标签: javajava-15java-record

解决方案


你不能。记录属性是不可变的。但是,您可以做的是添加一个 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());
    }
} 

推荐阅读