Google protocol buffers - user defined java objects as messages fields

java, serialization

Solution

No. It's only possible to use types defined as protocol buffers. (That said, it's common to implement your own complex classes as wrappers around protocol buffer classes, when you need to add more functionality.)

If you were really, really keen on it, you could use normal Java serialization (an `ObjectOutputStream` wrapped around a `ByteArrayOutputStream`), and then send the byte[] through the protocol buffers, though.

Problem

I am learning google protocol buffer since yesterday and have a question : Can i use a user-defined java class as a field type in a .proto file? Let me clarify my questions with the details below: 1 - I have following java class "MyComplexClass.java": ``` package mypackage; import another.package1.ClassA; import another.package2.ClassB; public class MyComplexClass { private ClassA var1; private ClassB var2; public MyComplexClass(ClassA X, ClassB Y) this.var1 = X; this.var2 = Y; } ``` 2- Now I would like to serialize an instance of the class "MyComplexClass.java". For that purpose, I would like to describe a message like the following in a .proto file: ``` message myMessageToBeSerialized { required ***MyComplexClass*** intanceOfComplexClass = 1; } ``` Is it possible to use the user-defined class MyComplexClass as a field type ? Or is it only allowed to use scalar types? Any help would be appreciated. Thanks in advance. Horace

Original source