{"record":{"id":"52124cc43a782215","repo":"apple/pkl","slug":"error-invoking-constructor-of-class-s-52124c","errorCode":null,"errorMessage":"Error invoking constructor of class `%s`.","messagePattern":"Error invoking constructor of class `(.+?)`\\.","errorType":"exception","errorClass":"ConversionException","httpStatus":null,"severity":"error","filePath":"pkl-config-java/src/main/java/org/pkl/config/java/mapper/PMapToMap.java","lineNumber":65,"sourceCode":"    var typeArguments = mapType.getActualTypeArguments();\n    var keyType = Reflection.normalize(typeArguments[0]);\n    var valueType = Reflection.normalize(typeArguments[1]);\n    return createInstantiator(targetClass)\n        .map(instantiator -> new ConverterImpl<>(instantiator, keyType, valueType));\n  }\n\n  private <K, V> Optional<Function<Integer, Map<K, V>>> createInstantiator(Class<?> clazz) {\n    try {\n      // constructor with capacity and load factor arguments\n      var ctor2 =\n          lookup.findConstructor(clazz, MethodType.methodType(void.class, int.class, float.class));\n      return Optional.of(\n          length -> {\n            try {\n              //noinspection unchecked\n              return (Map<K, V>) ctor2.invoke((int) (length / .75f) + 1, .75f);\n            } catch (Throwable t) {\n              throw new ConversionException(\n                  String.format(\"Error invoking constructor of class `%s`.\", clazz), t);\n            }\n          });\n    } catch (NoSuchMethodException e2) {\n      try {\n        // default constructor\n        var ctor0 = lookup.findConstructor(clazz, MethodType.methodType(void.class));\n        return Optional.of(\n            length -> {\n              try {\n                //noinspection unchecked\n                return (Map<K, V>) ctor0.invoke();\n              } catch (Throwable t) {\n                throw new ConversionException(\n                    String.format(\"Error invoking constructor of class `%s`.\", clazz), t);\n              }\n            });\n      } catch (NoSuchMethodException e0) {","sourceCodeStart":47,"sourceCodeEnd":83,"githubUrl":"https://github.com/apple/pkl/blob/f3efcbfc9b60d30053b0536d664948d7aa1b8673/pkl-config-java/src/main/java/org/pkl/config/java/mapper/PMapToMap.java#L47-L83","documentation":"PMapToMap maps a Pkl Map value to a Java Map implementation chosen by the requested target type. It instantiates the target map class via reflection, preferring a (int capacity, float loadFactor) constructor and passing (length/0.75f)+1 and 0.75f. This ConversionException wraps any Throwable thrown while invoking that two-argument constructor, such as an IllegalArgumentException from a constructor that rejects those arguments or an InvocationTargetException from constructor logic.","triggerScenarios":"Requesting a mapping to a Map subtype whose (int, float) constructor exists but fails when invoked during conversion, e.g. `ValueRenderer.render(config, my.CustomMap.class)` or DataFleet/Config conversions where CustomMap's (int,float) constructor validates its arguments or throws internally.","commonSituations":"Custom Map implementations whose capacity/load-factor constructor has different semantics (e.g. expects maxCapacity, not initialCapacity, and throws IllegalArgumentException for large sizes); constructors that throw on negative or oversized capacity for huge Pkl maps; constructors with side-effectful initialization that fails.","solutions":["Check the cause (`e.getCause()`) to see why the (int,float) constructor threw; fix the custom map class so its (int, float) constructor accepts initialCapacity and loadFactor semantics.","Add a no-arg constructor to your Map class so PMapToMap falls back to `createInstantiator`'s default-constructor path instead of the (int,float) constructor.","Map to a standard map type (java.util.HashMap, LinkedHashMap, TreeMap, SortedMap) whose (int,float) constructor is well-behaved.","If the constructor throws only for large inputs, reduce the size of the Pkl map or raise the limit inside the constructor."],"exampleFix":"// before\nclass Sizes extends HashMap<String, Integer> {\n  Sizes(int maxEntries, float unused) { super(maxEntries); if (maxEntries > 1000) throw new IllegalArgumentException(\"too big\"); }\n}\n// after\nclass Sizes extends HashMap<String, Integer> {\n  Sizes(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } // accept JDK semantics\n}","handlingStrategy":"try-catch","validationCode":"// Before conversion, verify the target map class has a well-behaved (int, float) constructor:\nstatic boolean hasSafeCapacityCtor(Class<?> c) {\n  try {\n    var ctor = c.getConstructor(int.class, float.class);\n    var inst = ctor.newInstance(4, 0.75f); // smoke-test invocation\n    inst.getClass().cast(inst);\n    return true;\n  } catch (ReflectiveOperationException | RuntimeException e) {\n    return false;\n  }\n}","typeGuard":"static boolean isStandardMap(Class<?> c) {\n  return java.util.HashMap.class.isAssignableFrom(c)\n      || java.util.LinkedHashMap.class.isAssignableFrom(c)\n      || java.util.TreeMap.class.isAssignableFrom(c);\n}","tryCatchPattern":"try {\n  Map<String, Object> result = valueRenderer.render(pValue, my.CustomMap.class);\n} catch (ConversionException e) {\n  Throwable cause = e.getCause();\n  log.error(\"Constructor of \" + cause + \" failed; falling back to HashMap\", e);\n  Map<String, Object> result = new java.util.LinkedHashMap<>(); // fallback\n}","preventionTips":["Give custom Map classes standard JDK constructor semantics: (int initialCapacity, float loadFactor) and a no-arg constructor that never throw.","Prefer standard JDK map types (HashMap, LinkedHashMap, SortedMap) as conversion targets.","Smoke-test reflective instantiation of custom target classes in unit tests before production use."],"tags":["java","reflection","map-conversion","constructor-invocation"],"backgroundTag":"invalid-constructor-argument","analyzedSha":"f3efcbfc9b60d30053b0536d664948d7aa1b8673","analyzedAt":"2026-09-08T13:10:45.570Z","contentChangedAt":"2026-09-08T13:10:45.570Z","schemaVersion":2},"datasetVersion":"2026-09-14T11:17:12.474Z"}