2015-04-27

Hiding protobuffer generated code in a Java library

In this post I describe how to hide Protocol Buffer's generated code in a Java library.

Recently, I was developing a Java library that used Google's Protocol Buffers as a serialization format. As part of the design of the library, we only expose some classes, the remaining implementation has package-private visibility. In particular, we de not want to exposed the generated object, as it was mapped into a domain class, but the protoc.exe executable produces public code. The solution was to perform a post-processing step invoking "protoc" to remove all public definitions used the sed command (if you are on Windows, you should have this command available by installing Git Bash). Here is an example of a batch file to this on Windows:

@echo off
:: compiling ProtoBuff definition
protoc.exe --java_out=java\ java\pt\invisibleobjects\MyObject.proto
:: setting package-private class visibility for classes
sed -i 's/^public final class/final class/' java\pt\invisibleobjects\MyObject.java
:: setting package-private class visibility for static classes
sed -i 's/^public static final class/static final class/' java\pt\invisibleobjects\MyObject.java
:: setting package-private class visibility for enums
sed -i 's/^public enum/enum/' java\pt\invisibleobjects\MyObject.java

No comments:

Post a Comment