const classafBeanUtils::TypeCoercer
sys::Obj afBeanUtils::TypeCoercer
@
Js
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 functionsoverride |Obj->Obj?|? createCoercionFunc(Type fromType, Type toType) { key := "${fromType.qname}->${toType.qname}" return cache.getOrAdd(key) { doCreateCoercionFunc(fromType, toType) } }** Clears the function cacheVoid clear() { cache.clear } }
- canCoerce
Bool canCoerce(Type? fromType, Type? toType)
Returns
true
iffromType
can be coerced to the giventoType
.If one of the supplied types is
null
, then the other has to be nullable.- coerce
Obj? coerce(Obj? value, Type toType)
Coerces (deeply) the Obj to the given type.
Coercion methods are looked up in the following order:
toXXX()
fromXXX()
makeFromXXX()
null
values are always coerced tonull
.