Class DefaultEnumMapper


  • public final class DefaultEnumMapper
    extends Object
    A default enum mapper that uses enum ordinal values to perform serialization and deserialization.

    This mapper encodes an enum constant into a byte by taking its Enum.ordinal(), and decodes a byte value back into the corresponding enum constant using array indexing. The encoding returns -1 for null inputs, and decoding returns null for negative codes. If a provided code is out of range (greater than or equal to the number of enum constants), an IllegalArgumentException is thrown.

    This class assumes that:

    • Enums have no more than 127 constants (to fit in a positive byte).
    • The order of enum constants (i.e., their ordinals) is stable and not subject to change.

    Example usage:

    
     public enum Color {
         RED, GREEN, BLUE;
     }
    
     Color[] values = Color.values();
     byte code = DefaultEnumMapper.INSTANCE.encode(Color.RED); // Returns 0
     Color color = DefaultEnumMapper.INSTANCE.decode(values, code); // Returns Color.RED
     

    Note: This class is thread-safe and uses a singleton pattern. Use INSTANCE to access the shared instance.

    See Also:
    Enum.ordinal()
    • Method Detail

      • encode

        public <T extends Enum<T>> byte encode​(T enumVal)
        Encodes the given enum value into a byte using its ordinal.
        Type Parameters:
        T - The enum type.
        Parameters:
        enumVal - The enum value to encode; may be null.
        Returns:
        The byte representation of the enum value (non-negative) or -1 if the value is null.
      • decode

        public <T extends Enum<T>> T decode​(T[] vals,
                                            byte enumCode)
        Decodes a byte code into the corresponding enum constant.
        Type Parameters:
        T - The enum type.
        Parameters:
        vals - Array of all possible values of the enum type. Must not be null.
        enumCode - The byte representation of the enum value.
        Returns:
        The corresponding enum constant, or null if enumCode is negative.
        Throws:
        IllegalArgumentException - if enumCode is out of range (i.e., greater than or equal to the length of vals array).