Home > Software design >  Java Protobuf nested class object creation
Java Protobuf nested class object creation

Time:08-06

syntax = "proto3";

package com.test.ps.speed.schema.v0;


message SpeedTestData {
    string segment_id = 1;
    repeated Speed speed = 2;

    message Speed {
        double start = 1;                       // Start offset
        repeated TimeStampEpoch timestamp_epoch = 3;
        repeated TimeStampUtc timestamp_utc = 4;
    }

    message TimeStampEpoch {
        uint64 source_capture_time = 1;         // Time when raw data was captured by Data Provider
        uint64 expiry_time = 2;                 // Time when the message expires
    }

    message TimeStampUtc {
        string source_capture_time = 1;         // Time when raw data was captured by Data Provider
        string expiry_time = 2;                 // Time when the message expires
    }


}

I have above protobuf structure. I want to add objects using Java and have written following code. I would like to add "TimeStampUtc" and "TimeStampEpoch" in objects, but due to nested structure I was not able to add. Little help will be appreciated.

Java code:

SpeedTestData.Speed newLastSpeed = SpeedTestData.Speed
                .newBuilder().setStart(2) // getting value from other class
                .setTimeStampEpoch()  // something like we need to add but could add due to nested structure
                .build();

CodePudding user response:

You are defining TimeStampUtc and TimeStampEpoch but it is not part of the SpeedTestData variables - that's why there is no setter method that you can use - it has nothing to do with being nested

Add the timestamp utc and epoch as variables like segment_id and speed and then regenerate the files

CodePudding user response:

Use the set*/add* methods, passing the submessage (or a builder of the submessage) as the argument:

SpeedTestData.newBuilder()
    .addSpeed(
        Speed.newBuilder()
            .setStart(2)
            .setTimestampEpoch(
                TimestampEpoch.newBuilder().setSourceCaptureTime(...))
    // ...
    .build()
  • Related