Class Codecs

java.lang.Object
com.dua3.utility.io.Codecs

public class Codecs extends Object
A registry for Codec instances.

Codecs are registered by calling registerCodec(Class, Encoder, Decoder). Registered codecs for a class can be obtained by using get(Class).

  • Constructor Details

    • Codecs

      public Codecs()
      Constructor. Default codecs for the Java primitive types are automatically registered.
  • Method Details

    • createCodec

      public static <T> Codec<T> createCodec(String name, Encoder<? super T> enc, Decoder<? extends T> dec)
      Create new Codec instance from Encoder and Decoder.
      Type Parameters:
      T - the object type
      Parameters:
      name - the codec name
      enc - the encoder
      dec - the decoder
      Returns:
      the new codec
    • collectionCodec

      public static <T, C extends Collection<T>> Codec<C> collectionCodec(String name, Codec<T> codec, IntFunction<? extends C> construct)
      Get Codec for a Collection.
      Type Parameters:
      T - the type of collection elements
      C - the collection type
      Parameters:
      name - the codec name
      codec - the element codec
      construct - collection factory method
      Returns:
      collection codec
    • mapEntryCodec

      public static <K, V> Codec<Map.Entry<K,V>> mapEntryCodec(Codec<K> codecK, Codec<? extends V> codecV)
      Get Codec for a Map.Entry.
      Type Parameters:
      K - the type of map keys
      V - the type of map values
      Parameters:
      codecK - the codec for keys
      codecV - the codec for values
      Returns:
      the map entry codec
    • mapCodec

      public static <K, V, M extends Map<K, V>> Codec<M> mapCodec(Codec<K> codecK, Codec<V> codecV, Supplier<? extends M> construct)
      Get Codec for a Map.
      Type Parameters:
      K - the key type
      V - the value type
      M - the map type
      Parameters:
      codecK - the key codec
      codecV - the value codec
      construct - the map construction method
      Returns:
      map codec
    • registerCodec

      public <T extends @Nullable Object> void registerCodec(Class<T> cls, Encoder<? super T> enc, Decoder<? extends T> dec)
      Register a codec for a specific class.
      Type Parameters:
      T - the class type
      Parameters:
      cls - the class to register the codec for
      enc - the encoder for the class
      dec - the decoder for the class
      Throws:
      IllegalArgumentException - if a codec is already registered for the class
    • get

      public <T> Optional<Codec<T>> get(Class<T> cls)
      Retrieves the codec registered for a specific class.
      Type Parameters:
      T - the class type
      Parameters:
      cls - the class to retrieve the codec for
      Returns:
      an Optional containing the codec, or an empty Optional if no codec is registered for the class