or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

core-messages.mdindex.mdio-wire-format.mdjson-text-format.mdreflection-descriptors.mdutilities.md
tile.json

tessl/maven-com-google-protobuf--protobuf-java

Google's Protocol Buffers implementation for Java, providing comprehensive serialization of structured data with efficient encoding and extensive API coverage

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/com.google.protobuf/protobuf-java@4.31.x

To install, run

npx @tessl/cli install tessl/maven-com-google-protobuf--protobuf-java@4.31.0

index.mddocs/

Protocol Buffers Java

Protocol Buffers Java (protobuf-java) is Google's official Java implementation of Protocol Buffers, providing a comprehensive solution for serializing structured data. It offers high-performance, language-neutral, platform-neutral serialization with strong type safety, compact binary format, and extensive compatibility guarantees across versions.

Package Information

  • Package Name: protobuf-java
  • Package Type: Maven
  • Language: Java
  • Group ID: com.google.protobuf
  • Artifact ID: protobuf-java
  • Installation: <dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java</artifactId><version>4.31.1</version></dependency>

Core Imports

import com.google.protobuf.Message;
import com.google.protobuf.MessageLite;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.InvalidProtocolBufferException;

For utility classes:

import com.google.protobuf.util.JsonFormat;
import com.google.protobuf.util.Timestamps;
import com.google.protobuf.util.Durations;
import com.google.protobuf.util.FieldMaskUtil;

Basic Usage

import com.google.protobuf.*;

// Working with ByteString for binary data
ByteString data = ByteString.copyFromUtf8("Hello Protocol Buffers");
byte[] bytes = data.toByteArray();
String text = data.toStringUtf8();

// Parsing protocol buffer messages (example with generated message)
try {
    // Parse from various sources
    MyMessage message1 = MyMessage.parseFrom(bytes);
    MyMessage message2 = MyMessage.parseFrom(inputStream);
    MyMessage message3 = MyMessage.parseFrom(codedInputStream);
    
    // Serialize messages
    ByteString serialized = message1.toByteString();
    byte[] serializedBytes = message1.toByteArray();
    
    // Build new messages
    MyMessage newMessage = MyMessage.newBuilder()
        .setField1("value")
        .setField2(123)
        .build();
        
} catch (InvalidProtocolBufferException e) {
    // Handle parsing errors
    System.err.println("Failed to parse: " + e.getMessage());
}

Architecture

Protocol Buffers Java is organized around several key components:

  • Message System: Core interfaces (MessageLite, Message) and abstract implementations providing the foundation for all protocol buffer messages
  • Serialization Engine: High-performance binary serialization using CodedInputStream/CodedOutputStream with wire format encoding
  • Type System: ByteString for efficient binary data handling, with immutable operations and zero-copy optimizations where possible
  • Reflection API: Complete runtime introspection through Descriptors for dynamic message handling and tooling
  • Extension System: Support for protocol buffer extensions with type-safe registration and access
  • Utility Layer: JSON conversion, timestamp/duration utilities, and field mask operations for common use cases

Capabilities

Core Message Interfaces and Serialization

Foundation interfaces and implementations for all protocol buffer messages, providing serialization, parsing, and builder patterns.

public interface MessageLite {
    void writeTo(CodedOutputStream output) throws IOException;
    int getSerializedSize();
    ByteString toByteString();
    byte[] toByteArray();
    Parser<? extends MessageLite> getParserForType();
    Builder newBuilderForType();
    Builder toBuilder();
}

public interface Message extends MessageLite, MessageOrBuilder {
    Parser<? extends Message> getParserForType();
    Builder newBuilderForType();
    Builder toBuilder();
}

Core Messages and Serialization

I/O and Wire Format Processing

Low-level binary I/O operations for reading and writing protocol buffer wire format data with support for all protocol buffer data types.

public abstract class CodedInputStream {
    static CodedInputStream newInstance(InputStream input);
    static CodedInputStream newInstance(byte[] buf);
    abstract int readTag();
    abstract int readInt32();
    abstract long readInt64();
    abstract String readString();
    abstract ByteString readBytes();
}

public abstract class CodedOutputStream {
    static CodedOutputStream newInstance(OutputStream output);
    static CodedOutputStream newInstance(byte[] flatArray);
    abstract void writeTag(int fieldNumber, int wireType);
    abstract void writeInt32(int fieldNumber, int value);
    abstract void writeString(int fieldNumber, String value);
    abstract void flush();
}

I/O and Wire Format

Binary Data Handling

Efficient immutable binary data operations with ByteString, providing string-like operations optimized for protocol buffer usage.

public abstract class ByteString {
    static final ByteString EMPTY;
    static ByteString copyFrom(byte[] bytes);
    static ByteString copyFromUtf8(String text);
    static ByteString readFrom(InputStream streamToDrain);
    
    abstract byte byteAt(int index);
    abstract int size();
    boolean isEmpty();
    ByteString substring(int beginIndex, int endIndex);
    ByteString concat(ByteString other);
    byte[] toByteArray();
    String toStringUtf8();
    boolean isValidUtf8();
}

Core Messages and Serialization

Runtime Reflection and Type Discovery

Comprehensive reflection API for runtime introspection of protocol buffer types, enabling dynamic message handling and tooling.

public static class Descriptors.FileDescriptor {
    String getName();
    String getPackage();
    List<Descriptor> getMessageTypes();
    List<EnumDescriptor> getEnumTypes();
    List<ServiceDescriptor> getServices();
    Descriptor findMessageTypeByName(String name);
}

public static class Descriptors.Descriptor {
    String getName();
    String getFullName();
    List<FieldDescriptor> getFields();
    List<Descriptor> getNestedTypes();
    FieldDescriptor findFieldByName(String name);
    FieldDescriptor findFieldByNumber(int number);
}

public static class Descriptors.FieldDescriptor {
    String getName();
    int getNumber();
    Type getType();
    boolean isRepeated();
    Object getDefaultValue();
}

Reflection and Descriptors

JSON Format Conversion

Bidirectional conversion between protocol buffers and JSON format with configurable options for field naming, default values, and type handling.

public static class JsonFormat.Printer {
    static Printer printer();
    Printer includingDefaultValueFields();
    Printer preservingProtoFieldNames();
    Printer omittingInsignificantWhitespace();
    String print(MessageOrBuilder message) throws InvalidProtocolBufferException;
}

public static class JsonFormat.Parser {
    static Parser parser();
    Parser ignoringUnknownFields();
    void merge(String json, Message.Builder builder) throws InvalidProtocolBufferException;
}

JSON and Text Format

Well-Known Types Utilities

Utility classes for working with protocol buffer well-known types like timestamps, durations, and field masks.

public class Timestamps {
    static final Timestamp EPOCH;
    static Timestamp fromMillis(long millis);
    static long toMillis(Timestamp timestamp);
    static Timestamp parseTimestamp(String value) throws ParseException;
    static String toString(Timestamp timestamp);
}

public class Durations {
    static final Duration ZERO;
    static Duration fromMillis(long millis);
    static long toMillis(Duration duration);
    static Duration parseDuration(String value) throws ParseException;
}

public class FieldMaskUtil {
    static FieldMask fromString(String value);
    static String toString(FieldMask fieldMask);
    static void merge(FieldMask mask, Message source, Message.Builder destination);
}

Utility Classes

Text Format and Debugging

Human-readable text format support for debugging, configuration files, and development workflows.

public static class TextFormat.Printer {
    static Printer printer();
    Printer escapingNonAscii(boolean escapeNonAscii);
    Printer usingTypeRegistry(TypeRegistry typeRegistry);
    String printToString(MessageOrBuilder message);
    void print(MessageOrBuilder message, Appendable output) throws IOException;
}

public static class TextFormat.Parser {
    static Parser getParser();
    void merge(Readable input, Message.Builder builder) throws IOException;
}

JSON and Text Format

Exception Handling

Protocol buffer operations can throw several specific exceptions:

public class InvalidProtocolBufferException extends IOException {
    InvalidProtocolBufferException(String description);
    MessageLite getUnfinishedMessage();
    InvalidProtocolBufferException setUnfinishedMessage(MessageLite unfinishedMessage);
}

Common scenarios:

  • InvalidProtocolBufferException: Thrown during parsing when data is malformed or incompatible
  • IOException: Thrown during I/O operations with streams
  • IllegalArgumentException: Thrown for invalid field numbers, null arguments, or malformed input

Performance Considerations

  • Use CodedInputStream/CodedOutputStream for high-performance streaming operations
  • ByteString provides zero-copy operations where possible - prefer over byte arrays for repeated operations
  • Lite runtime (protobuf-javalite) available for Android and memory-constrained environments
  • Message builders reuse internal arrays when possible - prefer builder patterns for construction
  • UnsafeByteOperations available for extreme performance scenarios (use with caution)

Thread Safety

  • Messages are immutable after construction and fully thread-safe
  • Builders are NOT thread-safe and should not be shared across threads
  • ByteString instances are immutable and thread-safe
  • Parsers are stateless and thread-safe
  • Extension registries should be configured before use and not modified during parsing

Types

// Core message lifecycle interfaces
public interface MessageLiteOrBuilder {}
public interface MessageOrBuilder extends MessageLiteOrBuilder {
    Object getField(Descriptors.FieldDescriptor field);
    boolean hasField(Descriptors.FieldDescriptor field);
    Descriptors.Descriptor getDescriptorForType();
}

// Builder interfaces
public interface MessageLite.Builder extends MessageLiteOrBuilder, Cloneable {
    MessageLite build();
    MessageLite buildPartial();
    MessageLite.Builder clear();
    MessageLite.Builder clone();
}

public interface Message.Builder extends MessageLite.Builder, MessageOrBuilder {
    Message build();
    Message buildPartial();
    Message.Builder clear();
    Message.Builder clone();
}

// Parsing interface
public interface Parser<MessageType extends MessageLite> {
    MessageType parseFrom(CodedInputStream input) throws InvalidProtocolBufferException;
    MessageType parseFrom(ByteString data) throws InvalidProtocolBufferException;
    MessageType parseFrom(byte[] data) throws InvalidProtocolBufferException;
}

// Extension support
public abstract class Extension<ContainingType extends MessageLite, Type> 
    extends ExtensionLite<ContainingType, Type> {}

public class ExtensionRegistryLite {
    static ExtensionRegistryLite newInstance();
    static ExtensionRegistryLite getEmptyRegistry();
}