2.2.2. Adding ProtoStream annotations to Java classes
Declare ProtoStream metadata by adding annotations to a Java class and its members. Data Grid then uses the ProtoStream processor to generate Protobuf schema and related marshallers from those annotations.
Procedure
Annotate the Java fields that you want to marshall with
@ProtoField, either directly on the field or on the getter or setter method.Any non-annotated fields in your Java class are transient. For example, you have a Java class with 15 fields and annotate five of them. The resulting schema contains only those five fields and only those five fields are marshalled when storing a class instance in Data Grid.
-
Use
@ProtoFactoryto annotate constructors for immutable objects. The annotated constructors must initialize all fields annotated with@ProtoField. -
Annotate members of any Java enum with
@ProtoEnumValue.
The following Author.java and Book.java examples show Java classes annotated with @ProtoField and @ProtoFactory:
Author.java
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
public class Author {
@ProtoField(1)
final String name;
@ProtoField(2)
final String surname;
@ProtoFactory
Author(String name, String surname) {
this.name = name;
this.surname = surname;
}
// public Getter methods omitted for brevity
}
Book.java
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
public class Book {
@ProtoField(number = 1)
public final UUID id;
@ProtoField(number = 2)
final String title;
@ProtoField(number = 3)
final String description;
@ProtoField(number = 4, defaultValue = "0")
final int publicationYear;
@ProtoField(number = 5, collectionImplementation = ArrayList.class)
final List<Author> authors;
@ProtoField(number = 6)
public Language language;
@ProtoFactory
Book(UUID id, String title, String description, int publicationYear, List<Author> authors, Language language) {
this.id = id;
this.title = title;
this.description = description;
this.publicationYear = publicationYear;
this.authors = authors;
this.language = language;
}
// public Getter methods not included for brevity
}
The following Language.java example shows a Java enum annotated with @ProtoEnumValue along with the corresponding Protobuf schema:
Language.java
import org.infinispan.protostream.annotations.ProtoEnumValue;
public enum Language {
@ProtoEnumValue(number = 0, name = "EN")
ENGLISH,
@ProtoEnumValue(number = 1, name = "DE")
GERMAN,
@ProtoEnumValue(number = 2, name = "IT")
ITALIAN,
@ProtoEnumValue(number = 3, name = "ES")
SPANISH,
@ProtoEnumValue(number = 4, name = "FR")
FRENCH;
}
Language.proto
enum Language {
EN = 0;
DE = 1;
IT = 2;
ES = 3;
FR = 4;
}