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

Set value to one of the property in Java 15 record

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

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

如果您需要改变属性,则需要使用 class 而不是 record

来自JEP

Enhance the Java programming language with records, which are classes that act as transparent carriers for immutable data. Records can be thought of as nominal tuples.

因此,如果您需要这种行为,最好使用 class。

您不能修改它们。来自 Oracle 页面:

A record class is a shallowly immutable, transparent carrier for a fixed set of values, called the record components. The Java language provides concise syntax for declaring record classes, whereby the record components are declared in the record header. The list of record components declared in the record header form the record descriptor.

从 Java 语言规范 Section 8.10 可以阅读以下内容:

A record declaration is implicitly final. It is permitted for the declaration of a record class to redundantly specify the final

8.10.3 记录成员

A record class has for each record component appearing in the record component list an implicitly declared field with the same name as the record component and the same type as the declared type of the record component. This field is declared private and final. The field is annotated with the annotations, if any, that appear on the corresponding record component and whose annotation types are applicable in the field declaration context, or in type contexts, or both.

你不能。记录属性是不可变的。然而,你可以做的是添加一个枯萎来创建一个具有相同属性但新 ID 的新记录:

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

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