{"record":{"id":"be14fc6abec34743","repo":"google/gson","slug":"unable-to-create-instance-of-rawtype-registeri","errorCode":null,"errorMessage":"Unable to create instance of ${rawType}. Registering an InstanceCreator or a TypeAdapter for this type, or adding a no-args constructor may fix this problem.","messagePattern":"Unable to create instance of (.+?)\\. Registering an InstanceCreator or a TypeAdapter for this type, or adding a no-args constructor may fix this problem\\.","errorType":"exception","errorClass":"RuntimeException","httpStatus":null,"severity":"error","filePath":"gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java","lineNumber":369,"sourceCode":"    }\n    // Then try ConcurrentNavigableMap implementation\n    else if (rawType.isAssignableFrom(ConcurrentSkipListMap.class)) {\n      return ConcurrentSkipListMap::new;\n    }\n\n    // Was unable to create matching Map constructor\n    return null;\n  }\n\n  private <T> ObjectConstructor<T> newUnsafeAllocator(Class<? super T> rawType) {\n    if (useJdkUnsafe) {\n      return () -> {\n        try {\n          @SuppressWarnings(\"unchecked\")\n          T newInstance = (T) UnsafeAllocator.INSTANCE.newInstance(rawType);\n          return newInstance;\n        } catch (Exception e) {\n          throw new RuntimeException(\n              (\"Unable to create instance of \"\n                  + rawType\n                  + \". Registering an InstanceCreator or a TypeAdapter for this type, or adding a\"\n                  + \" no-args constructor may fix this problem.\"),\n              e);\n        }\n      };\n    } else {\n      String exceptionMessage =\n          \"Unable to create instance of \"\n              + rawType\n              + \"; usage of JDK Unsafe is disabled. Registering an InstanceCreator or a TypeAdapter\"\n              + \" for this type, adding a no-args constructor, or enabling usage of JDK Unsafe may\"\n              + \" fix this problem.\";\n\n      // Check if R8 removed all constructors\n      if (rawType.getDeclaredConstructors().length == 0) {\n        // R8 with Unsafe disabled might not be common enough to warrant a separate Troubleshooting","sourceCodeStart":351,"sourceCodeEnd":387,"githubUrl":"https://github.com/google/gson/blob/310ac341f2f92a454b229bf21f70d2d18b2b6db7/gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java#L351-L387","documentation":"Thrown when Gson falls back to JDK Unsafe (sun.misc.Unsafe.allocateInstance) to create an object — because there is no no-args constructor and no InstanceCreator — and Unsafe itself throws. UnsafeAllocator tries three strategies (sun.misc.Unsafe, Dalvik ObjectStreamClass, pre-gingerbread ObjectInputStream) and may fall back to an implementation that throws UnsupportedOperationException, or the reflective Unsafe lookup may fail.","triggerScenarios":"useJdkUnsafe is enabled (default), the class has no accessible no-args constructor, no InstanceCreator, and UnsafeAllocator.INSTANCE.newInstance() fails — Unsafe unavailable on the runtime, module access blocked (JDK 16+ strong encapsulation), or the class can't be allocated via Unsafe.","commonSituations":"Android runtimes without sun.misc.Unsafe; JDK 16+ where sun.misc.Unsafe access is restricted; exotic JVMs; classes Unsafe refuses to instantiate (arrays, primitives).","solutions":["Add a no-args constructor to the class so Gson doesn't need Unsafe","Register an InstanceCreator for the type to control construction","Register a custom TypeAdapter for the type","If on JDK 16+, add --add-opens java.base/sun.misc=ALL-UNNAMED (less safe) or migrate to explicit constructors"],"exampleFix":"// before\nclass Foo {\n  public Foo(String x) {} // only ctor, no no-args\n}\n\n// after\nclass Foo {\n  public Foo() {}        // Gson uses this\n  public Foo(String x) {}\n}","handlingStrategy":"validation","validationCode":"// Verify a no-args constructor exists before relying on Unsafe fallback\nClass<?> c = MyType.class;\ntry {\n  c.getDeclaredConstructor();\n} catch (NoSuchMethodException e) {\n  // Unsafe will be attempted; register InstanceCreator to avoid fragility\n  gsonBuilder.registerTypeAdapter(c, (InstanceCreator<MyType>) t -> new MyType(defaultArg));\n}","typeGuard":null,"tryCatchPattern":"try {\n  return gson.fromJson(json, MyType.class);\n} catch (RuntimeException e) {\n  if (e.getMessage() != null && e.getMessage().startsWith(\"Unable to create instance\")) {\n    // Unsafe failed; provide InstanceCreator and retry\n    throw new MyParseException(\"Unsafe allocation failed for \" + MyType.class, e);\n  }\n  throw e;\n}","preventionTips":["Always add a no-args constructor to classes Gson deserializes, avoiding Unsafe entirely","Register InstanceCreators for classes without no-args constructors","On JDK 16+ or Android, don't rely on sun.misc.Unsafe — it may be unavailable","Consider disableJdkUnsafe() in tests to catch missing constructors early"],"tags":["constructor","unsafe","reflection","instantiation","jdk16"],"backgroundTag":null,"analyzedSha":"310ac341f2f92a454b229bf21f70d2d18b2b6db7","analyzedAt":"2026-08-10T02:58:47.455Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}