{"record":{"id":"aa4d218ff1b59431","repo":"apple/pkl","slug":"error-invoking-constructor-of-class-s","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/PCollectionToCollection.java","lineNumber":61,"sourceCode":"\n    return createInstantiator(targetClass)\n        .map(instantiator -> new ConverterImpl<>(instantiator, elementType));\n  }\n\n  private <T> Optional<Function<Integer, Collection<T>>> createInstantiator(Class<T> clazz) {\n    try {\n      try {\n        // constructor with capacity and load factor parameters, e.g. HashSet\n        var ctor2 =\n            lookup.findConstructor(\n                clazz, MethodType.methodType(void.class, int.class, float.class));\n        return Optional.of(\n            length -> {\n              try {\n                //noinspection unchecked\n                return (Collection<T>) 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          // constructor with size parameter, e.g. ArrayList\n          var ctor1 = lookup.findConstructor(clazz, MethodType.methodType(void.class, int.class));\n          return Optional.of(\n              length -> {\n                try {\n                  //noinspection unchecked\n                  return (Collection<T>) ctor1.invoke(length);\n                } catch (Throwable t) {\n                  throw new ConversionException(\n                      String.format(\"Error invoking constructor of class `%s`.\", clazz), t);\n                }\n              });\n        } catch (NoSuchMethodException e1) {","sourceCodeStart":43,"sourceCodeEnd":79,"githubUrl":"https://github.com/apple/pkl/blob/f3efcbfc9b60d30053b0536d664948d7aa1b8673/pkl-config-java/src/main/java/org/pkl/config/java/mapper/PCollectionToCollection.java#L43-L79","documentation":"Thrown by PCollectionToCollection.createInstantiator when a Pkl collection (List/Set/Map) is mapped to a Java Collection type. The mapper reflectively invokes the target collection class's two-arg constructor `(int initialCapacity, float loadFactor)` (typical for HashMap/HashSet); if the reflective `ctor2.invoke(...)` call throws any Throwable (instantiation failure, IllegalArgumentException from bad capacity, constructor throwing internally), it is wrapped in this ConversionException.","triggerScenarios":"Mapping a Pkl collection to a custom Collection/Map class whose `(int, float)` constructor throws — e.g. a constructor that validates capacity and rejects the computed value `(int)(length / .75f) + 1`, or an abstract/uninstantiable class reached via a custom mapping target.","commonSituations":"Custom collection implementations with guarded constructors (negative/zero-capacity checks failing for empty Pkl collections); classes whose constructors have side effects (required config, DB connections) that fail; third-party collection libs with strict invariants.","solutions":["Inspect the wrapped cause (`getCause()`) — the real failure is inside the target class's (int, float) constructor; fix that constructor or its preconditions.","Map to a standard collection type (java.util.ArrayList/HashMap/LinkedHashSet) instead of the custom class.","If a custom class is required, provide an accessible no-arg or `(int)` constructor that does not throw for the computed initial capacity.","Register a custom Converter for that target type instead of relying on reflective instantiation."],"exampleFix":"// before\npublic MySet(int cap, float lf) { if (cap < 10) throw new IllegalArgumentException(\"cap too small\"); ... }\n// after\npublic MySet(int cap, float lf) { super(Math.max(16, cap), lf); }","handlingStrategy":"try-catch","validationCode":"// ensure the target class has a working (int, float) constructor:\nClass<?> c = targetClass; c.getConstructor(int.class, float.class).newInstance(16, 0.75f);","typeGuard":null,"tryCatchPattern":"try { MyConfig cfg = mapper.map(module, MyConfig.class); } catch (ConversionException e) { Throwable real = e.getCause(); log.error(\"Constructor of {} failed: {}\", e.getMessage(), real, real); }","preventionTips":["Inspect getCause() first — the real failure is inside the target constructor","Prefer standard JDK collections as mapping targets","Make custom collection constructors side-effect free","Keep custom collection constructors tolerant of small/zero initial capacities"],"tags":["pkl","java","reflection","collection","constructor"],"backgroundTag":"reflective-constructor-invocation-failed","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"}