Google Protocol Buffers, how to handle multiple message-Types?
java, protocol-buffers
Solution
We cannot determine if the file contains a Address or a User. Because there is not type information encoded in the data.
To handle multiple Message-Types, you can use meta data like:
- Extension of the filename
- Headers in HTTP
- Specific frame header in frame base stream protocol
- ...
Problem
Is it possible to get the Type of the serialized Protocol Buffer message? I have this example ``` option java_outer_classname="ProtoUser"; message User { required int32 id = 1; required string name = 2; required string firstname = 3; required string lastname = 4; required string ssn= 5; } message Address { required int32 id = 1; required string country = 2 [default = "US"];; optional string state = 3; optional string city = 4; optional string street = 5; optional string zip = 6; } ``` In Java I have this code ``` Address addr = ProtoUser.Address.newBuilder().setCity("Weston").setCountry("USA").setId(1).setState("FL").setStreet("123 Lakeshore").setZip("90210") .build(); User user = ProtoUser.User.newBuilder().setId(1).setFirstname("Luis").setLastname("Atencio").setName("luisat").setSsn("555-555-5555").build(); if(....){ FileOutputStream output = new FileOutputStream("out1.ser"); user.writeTo(output); output.close(); }else{ FileOutputStream output = new FileOutputStream("out1.ser"); addr.writeTo(output); output.close(); } ``` Now, can I determine if the file contains a Address or a User? What is the common way to handle multiple Message-Types? How can I determine which Message-Type I have received?