字段类型元信息
字段类型元信息配置用于控制结构体字段序列化时是否写入类型信息。 This is essential for supporting polymorphism where the actual runtime type may differ from the declared field type.
概述
When serializing a struct field, Fory needs to determine whether to write type metadata:
- Static typing: Use the declared field type's serializer directly (no type info written)
- Dynamic typing: Write type information to support runtime subtypes
何时需要类型元信息
Type metadata is required when:
- Interface/abstract fields: The declared type is abstract, so concrete type must be recorded
- Polymorphic fields: The runtime type may be a subclass of the declared type
- Cross-language compatibility: When the receiver needs type information to deserialize correctly
Type metadata is NOT needed when:
- Final/concrete types: The declared type is final/sealed and cannot be subclassed
- Primitive types: Type is known at compile time
- Performance optimization: When you know the runtime type always matches the declared type
各语言配置
Java
Java requires explicit configuration because concrete classes can be subclassed unless marked final.
Use the @ForyField annotation with the dynamic parameter:
import org.apache.fory.annotation.ForyField;
import org.apache.fory.annotation.ForyField.Dynamic;
public class Container {
// AUTO (default): Interface types write type info, concrete types don't
@ForyField(id = 0)
private Shape shape; // Interface - type info written
// FALSE: Never write type info (use declared type's serializer)
@ForyField(id = 1, dynamic = Dynamic.FALSE)
private Circle circle; // Always treated as Circle
// TRUE: Always write type info (support runtime subtypes)
@ForyField(id = 2, dynamic = Dynamic.TRUE)
private Shape concreteShape; // Type info written even if concrete
}
Dynamic Options:
| Value | Behavior |
|---|---|
AUTO | Interface/abstract types are dynamic, concrete are not |
FALSE | Never write type info, use declared type's serializer |
TRUE | Always write type info to support runtime subtypes |
Use Cases:
AUTO: Default behavior, suitable for most casesFALSE: Performance optimization when you know the exact typeTRUE: When a concrete field may hold subclass instances