Reputation: 1208
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
Upvotes: 4
Views: 4474
Reputation: 600
Yes you can. Define both ClassA and ClassB as messages and you can refer to them as field types in MyComplexClass. See below. (Define all 3 packages in seperate .proto files)
package another.package1;
message ClassA
{
<fields>
}
package another.package2;
message ClassB
{
<fields>
}
package mypackage;
import another/package1/ClassA;
import another/package2/ClassB;
message MyComplexClass
{
required ClassA var1 = 1;
required ClassB var2 = 2;
}
Upvotes: 1
Reputation: 70931
Simply define a proxy class that implements the conversion from the protocol buffer class to your class and vice versa.
Upvotes: 0
Reputation: 198023
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.
Upvotes: 4