/// <summary> /// throws MissingMethodsException atm, if a constructor could not be found. /// </summary> internal static Constructor GetBestMatchingConstructor(Type type, object[] args) { Constructor bestMatch = null; int bestMatchScore = int.MinValue; // this code does not take into account nullable structs. // this could be provided as well easily, if anybody ever cares... foreach (var c in ReflectionCache.JavaGetDeclaredConstructors(type)) { var cargs = c.ParameterTypes; if (cargs.Length != args.Length) { continue; } int match = 0; for (int i = 0; i < args.Length; ++i) { if (args[i] == null) { if (cargs[i].IsValueType) { goto nomatch; } continue; } var argType = args[i].GetType(); if (cargs[i] == argType) { match += 3; } else if (cargs[i].IsAssignableFrom(argType)) { match += 1; } else if (cargs[i].IsAssignableFrom(TypeHelper.EnsurePrimitiveType(type))) { match += 2; } else { goto nomatch; } } if (match > bestMatchScore) { bestMatchScore = match; bestMatch = c; } nomatch :; } if (bestMatch != null) { return(bestMatch); } var argumentTypes = args.Select(a => a == null ? "null" : a.JavaGetClass().FullName); string msg = string.Format("Could not find a matching constructor for type {0}({1})", type.FullName, string.Join(",", argumentTypes)); throw new MissingMethodException(msg); }