Class CastUtils

java.lang.Object
org.saidone.utils.CastUtils

public class CastUtils extends Object
Utility class providing methods for casting collections to specific generic types.

The helpers in this class convert loose Object instances into typed List and Map representations. Inputs are expected to already contain compatible elements; otherwise a ClassCastException will be raised by the casting operations. When null is provided, the methods return empty collections instead of null.

  • Constructor Details

    • CastUtils

      public CastUtils()
  • Method Details

    • castToListOfObjects

      public <T> List<T> castToListOfObjects(Object object, Class<T> elementType)
      Casts an object to a List containing elements of the requested type.

      The input must already be a List; otherwise an IllegalArgumentException is thrown. Each element is cast using Class.cast(Object), so incompatible entries trigger a ClassCastException. When null is supplied, an empty list is returned.

      Parameters:
      object - the input value expected to be a List
      elementType - the desired element type
      Returns:
      a list containing elements cast to elementType, or an empty list when the input is null
      Throws:
      IllegalArgumentException - if object is not a List
      ClassCastException - if any element cannot be cast to elementType
    • castToMapOfObjectObject

      public <KT, KV> Map<KT,KV> castToMapOfObjectObject(Object object, Class<KT> keyType, Class<KV> valueType)
      Casts an object to a Map with String keys and values of the requested Serializable type.

      The input must be a Map; otherwise an IllegalArgumentException is thrown. Keys are cast to String and values to valueType, so incompatible entries cause ClassCastExceptions. When null is provided, an empty map is returned.

      Parameters:
      object - the input value expected to be a Map
      keyType - the expected key type
      valueType - the expected value type
      Returns:
      a map containing entries cast to the requested types, or an empty map when the input is null
      Throws:
      IllegalArgumentException - if object is not a Map
      ClassCastException - if any key or value cannot be cast to the requested types