GlidingSwords997
GlidingSwords997

Reputation: 85

Error while casting java.util.Collections$UnmodifiableRandomAccessList to com.google.protobuf.Message

I am getting a response from a gRPC call in the form of Dynamic Message, which has nested fields. For that, I am trying to get the first level field first, and then using this object to fetch the nested fields, this is how the response looks:

field1 {
  key1: "value1"
}
field2 {
  key1: "value1"
  key2: value2
  key3 {
    netsed_key_1: "nested_val_1"
    netsed_key_2: "nested_val_2"
  }
  key4 {
    netsed_key_1: "nested_val_1"
    netsed_key_2: "nested_val_2"
  }
}

So, what happens is when I fetch based on field2, I get this:

key1: "value1"
  key2: value2
  key3 {
    netsed_key_1: "nested_val_1"
    netsed_key_2: "nested_val_2"
  }
  key4 {
    netsed_key_1: "nested_val_1"
    netsed_key_2: "nested_val_2"
  }

The response belongs to the Object class. But, now to get the nested fields, I need to typecast it to Message, as I will be using the library method:

FieldDescriptor fieldDescriptor = message.getDescriptorForType().findFieldByName("nested_key_1");

But when I try to cast the Object to the Message class, I get this error: description=Failed to read message., cause=java.lang.ClassCastException: java.util.Collections$UnmodifiableRandomAccessList cannot be cast to com.google.protobuf.Message

Is there any other way to do this typecasting ?

Object subMessage =
                message.getField(message.getDescriptorForType().findFieldByName("field2"));
 Message sub = (Message) subMessage;
 Object subSubMessage =
             sub.getField(sub.getDescriptorForType().findFieldByName("nested_key_1"));
            System.out.println(subMessage + " " + subSubMessage);

Here I get the casting exception.

Upvotes: 0

Views: 583

Answers (1)

Eugene
Eugene

Reputation: 9474

Looks like field2 is a repeated field. Cast it to java.util.List and access individual objects through the collection.

Upvotes: 1

Related Questions