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

Back to the Future

I've recently decided to close my old personal blog. However, I picked all the software development related posts (wrote somewhere between 2007 and 2008) and imported them into this blog.