Enum Configuration
This page explains how Java enum serialization is configured in Apache Fory.
Default Enum Behavior
Java enums can be serialized in two modes:
- By numeric tag: the default behavior
- By enum name: enabled with
serializeEnumByName(true)
Numeric tags are always used in xlang mode. In native Java mode, serializeEnumByName(true)
switches enum serialization to names instead of numeric tags.
Serialize Enums by Name
Use serializeEnumByName(true) when native Java peers should match enum constants by name instead
of numeric tag.
Fory fory = Fory.builder()
.withLanguage(Language.JAVA)
.serializeEnumByName(true)
.build();
This mode is useful when declaration order is unstable but enum names remain fixed. It only affects native Java mode. Xlang still uses numeric tags.
Stable Numeric Enum IDs
Without serializeEnumByName(true), Java enums are serialized by numeric tag. The default tag is
the declaration ordinal. When an enum needs stable ids that do not depend on declaration order,
annotate exactly one id source with @ForyEnumId, or annotate every enum constant with explicit
tag values.
import org.apache.fory.annotation.ForyEnumId;
enum Status {
Unknown(10),
Running(20),
Finished(30);
private final int id;
Status(int id) {
this.id = id;
}
@ForyEnumId
public int getId() {
return id;
}
}
Java also supports annotating one enum instance field with @ForyEnumId, or annotating every enum
constant directly such as @ForyEnumId(10) Unknown.
@ForyEnumId Styles
@ForyEnumId supports exactly three configuration styles:
- Annotate one enum instance field and store the numeric id there.
- Annotate one zero-argument public instance method such as
getId(). - Annotate every enum constant directly with an explicit value such as
@ForyEnumId(10) Unknown.
Validation Rules
- Use exactly one of those three styles for a given enum.
- Field and method annotations must leave
value()at its default-1. - Enum-constant annotations must appear on every constant once any constant uses
@ForyEnumId. - All ids must be non-negative, unique, and fit in Java
int.
Lookup Behavior
- Without
@ForyEnumId, Fory writes the declaration ordinal. - With
@ForyEnumId, Fory writes the configured stable numeric tag instead. - Small dense tags use an array lookup internally; sparse larger tags fall back to a map.
Choosing Between Name and Numeric Modes
- Use enum names when the enum is Java-only and constant names are the intended compatibility key.
- Use numeric tags when cross-language payloads or stable explicit ids matter.
- Use
@ForyEnumIdwhen declaration order may change but the numeric wire ids must stay stable.
Related Topics
- Configuration -
serializeEnumByNameand other runtime options - Field Configuration -
@ForyField,@Ignore, and integer encoding annotations - Cross-Language - Xlang enum interoperability