const classafBeanUtils::TypeCoercer

sys::Obj
  afBeanUtils::TypeCoercer

Coerces objects to a given type via fromXXX() / toXXX() ctors and methods. This is often useful for converting objects to and from Strs, but can be used for much more.

TypeCoercer inspects type parameters in Lists and Maps and also converts the contents of each. Example, coercing Int[1, 2, 3] to Str[] will convert each item of the list into a Str. Similarly, when coercing a map to a new map type, all the key and vals will be converted.

The caseInsensitive and ordered attributes of new maps are preserved.

If performance is required, then use Concurrent to create a TypeCoercer that caches the functions used to convert between one type and another. Full code for a CachingTypeCoercer is given below:

using afBeanUtils
using afConcurrent

** A 'TypeCoercer' that caches its conversion methods.
const class CachingTypeCoercer : TypeCoercer {
   private const AtomicMap cache := AtomicMap()

   ** Cache the conversion functions
   override protected |Obj->Obj|? createCoercionFunc(Type fromType, Type toType) {
      key := "${fromType.qname}->${toType.qname}"
      return cache.getOrAdd(key) { doCreateCoercionFunc(fromType, toType) } 
   }

   ** Clears the function cache 
   Void clear() {
      cache.clear
   }
}
canCoerce

Source

Bool canCoerce(Type fromType, Type toType)

Returns true if fromType can be coerced to the given toType.

coerce

Source

Obj? coerce(Obj? value, Type toType)

Coerces the Obj to the given type. Coercion methods are looked up in the following order:

  1. toXXX()
  2. fromXXX()
  3. makeFromXXX()