Create jar from Proto files
Protobuf is one of the formats used by programs to communicate with each other over a network. It is Google’s IDL (Interface definition language) to describe the structure of any data which then can be used to generate source code to parse a stream of bytes that represent that structured data.
Demo
Following is a demo of how to create a jar file out of proto files.
In this blog we will use a gradle plugin to generate Java class files from a .proto file.
Create a sample gradle project in intellij:
Add following ‘buildscript’ config in the gradle:
buildscript { repositories { mavenCentral() } dependencies { classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.12' } }
Add ‘apply plugin’:
apply plugin: 'com.google.protobuf'
Following are the tasks that will be added to the gradle tasks list:
Below is an example of a sample cart.proto file added under ‘proto’ folder inside ‘main’ directory. Note that ‘java_package’ and ‘java_multiple_files’ are attributes to provide guidance to the protobuf compiler while generating class files.
Now when we run the generateProto task as shown below, we can see it has generated the corresponding Java files which will be present under the ‘generated’ folder inside build directory.
Add following dependency in the project:
dependencies { implementation 'com.google.protobuf:protobuf-java:3.11.4' }
Once added, run the ‘jar’ task in gradle and check the build/libs directory. The jar task will generate the jar with compiled class files:
The generated jar can be used by any java application to read or create the corresponding proto message in JVM.