Google's Protocol Buffers implementation for Java, providing comprehensive serialization of structured data with efficient encoding and extensive API coverage
npx @tessl/cli install tessl/maven-com-google-protobuf--protobuf-java@4.31.0Protocol 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.
<dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java</artifactId><version>4.31.1</version></dependency>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;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());
}Protocol Buffers Java is organized around several key components:
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
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();
}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
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();
}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;
}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);
}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;
}Protocol buffer operations can throw several specific exceptions:
public class InvalidProtocolBufferException extends IOException {
InvalidProtocolBufferException(String description);
MessageLite getUnfinishedMessage();
InvalidProtocolBufferException setUnfinishedMessage(MessageLite unfinishedMessage);
}Common scenarios:
// 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();
}