Why does Protobuf generate outer classes for Java?

2,975 views
Skip to first unread message

Matt Welke

unread,
Jul 25, 2021, 2:13:02 PM7/25/21
to Protocol Buffers

I googled this and found questions like "How to use Protobuf message as java class without a java outer class?" (https://stackoverflow.com/questions/60312156/how-to-use-protobuf-message-as-java-class-without-a-java-outer-class) which talk about how one might tweak their Protobuf Java code generation. For example, that person wants to avoid having outer classes. The answer tells them about the "multiple files" option.

But I'd like to know why the Java generated code, by default, is split up this way. I didn't notice code split up like that when I used my same Protobuf files to generate Go code. I got just one struct per Protobuf message I defined. In Java, I get two classes per Protobuf message defined, and I can choose between them being nested or in separate files. Why?

Deanna Garcia

unread,
Jul 26, 2021, 1:05:50 PM7/26/21
to Protocol Buffers
Java protobufs originally only had the option to have the outer class, which is consistent with some other languages' protocol buffers. We decided to add the "multiple files" option for users to have the option. We recommend using the multiple files option in most instances, but continue providing both in case historic users are reliant on having the outer class or if there are special cases in which a single file would be better.

Matt Welke

unread,
Jul 26, 2021, 2:49:59 PM7/26/21
to Protocol Buffers
Oh okay. So it sounds like many languages, including Java, originally generated code where every message's type was placed into a single generated file (a file per .proto file). For Java, you can only have one public class per file, so the outer class technique was used so that it could be the single public class in the generated file, with each message's class as an inner class within the outer class.

But then some users wanted the option of splitting up the generated code, which let to the Java option to use multiple files, in which case there's no need for the outer class technique.

So the outer class technique wasn't to enable any specific Protobuf feature, it was just to work around the limitations of Java to make the code look like the code generated when using other languages.

Reply all
Reply to author
Forward
0 new messages