You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GRPC:如何在消息构建完成后设置/修改字段

实现方式

gRPC生成的消息实例是不可变对象,调用build()后无法直接修改内部字段,要实现你想要的updateCheckInTime调用方式,有两种可行方案:

方案一:封装自定义更新方法(贴合你的调用预期)

根据使用的语言,封装对应方法来实现你想要的调用形式:

Java 静态工具类实现

public class HotelRoomReservationHelper {
    public static HotelRoomReservation updateCheckInTime(HotelRoomReservation reservation, Timestamp newCheckInTime) {
        return reservation.toBuilder()
                .setCheckInTime(newCheckInTime)
                .build();
    }
}

调用方式:

reservation = HotelRoomReservationHelper.updateCheckInTime(reservation, newCheckInTime);

Kotlin 扩展函数实现

fun HotelRoomReservation.updateCheckInTime(newCheckInTime: Timestamp): HotelRoomReservation {
    return this.toBuilder()
        .setCheckInTime(newCheckInTime)
        .build()
}

调用方式完全符合你的预期:

reservation = reservation.updateCheckInTime(newCheckInTime)

方案二:直接使用原生toBuilder()方法

不想额外封装的话,直接用gRPC消息自带的toBuilder()接口,先将不可变实例转为Builder对象,修改字段后重新构建新实例:

reservation = reservation.toBuilder()
        .setCheckInTime(newCheckInTime)
        .build();

关键注意点

  • 无论哪种方案,最终都会生成新的消息实例,原实例因不可变特性不会被修改,因此需要将新实例重新赋值给变量。
  • 如果字段是Protobuf的optional类型,直接调用setCheckInTime就会覆盖原有值,无需额外清空操作。

内容的提问来源于stack exchange,提问作者TheRealFakeNews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:25:27