createInstanceWithConstructor method

O? createInstanceWithConstructor(
  1. ConstructorReflection<O> constructor,
  2. Map<String, Object?> map, {
  3. FieldNameResolver? fieldNameResolver,
  4. FieldValueResolver? fieldValueResolver,
  5. OnConstructorInvocationError? onInvocationError,
})

Creates an instance with constructor using map entries as parameters.

Implementation

O? createInstanceWithConstructor(
    ConstructorReflection<O> constructor, Map<String, Object?> map,
    {FieldNameResolver? fieldNameResolver,
    FieldValueResolver? fieldValueResolver,
    OnConstructorInvocationError? onInvocationError}) {
  var usesJsonNameAlias = hasJsonNameAlias;

  var methodInvocation = constructor.methodInvocationFromMap(map,
      reviver: fieldValueResolver,
      nameResolver: fieldNameResolver,
      jsonName: usesJsonNameAlias);

  try {
    var o = methodInvocation.invoke(constructor.constructor);
    return o;
  } catch (e) {
    // Tries a second parameter resolution if some value was resolved.
    // This will allow use of the current cached entities in a `JsonEntityCache`
    // (if used by `fieldValueResolver`).
    var map2 = methodInvocation.parametersToMap();

    if (!DeepCollectionEquality().equals(map, map2)) {
      var methodInvocation2 = constructor.methodInvocationFromMap(map2,
          reviver: fieldValueResolver,
          nameResolver: fieldNameResolver,
          jsonName: usesJsonNameAlias);

      try {
        var o = methodInvocation2.invoke(constructor.constructor);
        return o;
      } catch (e2) {
        if (onInvocationError != null) {
          onInvocationError(constructor, methodInvocation2, map2, e2);
        } else {
          rethrow;
        }
      }
    } else {
      if (onInvocationError != null) {
        onInvocationError(constructor, methodInvocation, map, e);
      } else {
        rethrow;
      }
    }
  }

  return null;
}