• Uncategorised
  • 0

Java Example: Using Protocol Buffers

This example shows how to define, compile, serialize, and deserialize a Protocol Buffers (Protobuf) message in Java.


📌 Step 1: Define the Protobuf Schema

Create a file named person.proto:

syntax = "proto3";

package example;

// Generate Java classes inside `example` package
option java_package = "com.example.protobuf";
option java_outer_classname = "PersonProto";

message Person {
  string name = 1;
  int32 age = 2;
  repeated string emails = 3;
}

Explanation:

  • syntax = "proto3"; → Specifies we are using Protobuf 3.
  • option java_package = "com.example.protobuf"; → Java package where the generated code will go.
  • message Person {} → Defines a Person structure.
  • repeated string emails = 3; → A list of emails (like List<String> in Java).

📌 Step 2: Compile the Protobuf File

Run the Protobuf Compiler (protoc) to generate Java code:

protoc --java_out=src/main/java person.proto

This generates a Java file:
com/example/protobuf/PersonProto.java


📌 Step 3: Add Protobuf Dependency in pom.xml

If you use Maven, add this to your pom.xml:

xmlCopyEdit
<dependencies>
    <!-- Protobuf Java Runtime -->
    <dependency>
        <groupId>com.google.protobuf</groupId>
        <artifactId>protobuf-java</artifactId>
        <version>3.21.12</version>
    </dependency>
</dependencies>

📌 Step 4: Use Protobuf in Java

Now, write Java code to serialize and deserialize Protobuf messages.

✅ Serialization (Convert Object to Bytes)

import com.example.protobuf.PersonProto.Person;
import java.io.FileOutputStream;
import java.io.IOException;

public class ProtobufSerialization {
    public static void main(String[] args) {
        try {
            // Create a Person object
            Person person = Person.newBuilder()
                    .setName("John Doe")
                    .setAge(30)
                    .addEmails("[email protected]")
                    .addEmails("[email protected]")
                    .build();

            // Serialize to byte array
            byte[] data = person.toByteArray();
            System.out.println("Serialized Data: " + data.length + " bytes");

            // Save to file
            FileOutputStream output = new FileOutputStream("person.bin");
            person.writeTo(output);
            output.close();
            System.out.println("Protobuf file written successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Deserialization (Convert Bytes to Object)

import com.example.protobuf.PersonProto.Person;
import java.io.FileInputStream;
import java.io.IOException;

public class ProtobufDeserialization {
    public static void main(String[] args) {
        try {
            // Read from file
            FileInputStream input = new FileInputStream("person.bin");
            Person person = Person.parseFrom(input);
            input.close();

            // Print the deserialized object
            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
            System.out.println("Emails: " + person.getEmailsList());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *