google/gson · error · RuntimeException

Unable to create instance of ${rawType}. Registering an Inst

Error message

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.

What it means

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.

Source

Thrown at gson/src/main/java/com/google/gson/internal/ConstructorConstructor.java:369

    }
    // Then try ConcurrentNavigableMap implementation
    else if (rawType.isAssignableFrom(ConcurrentSkipListMap.class)) {
      return ConcurrentSkipListMap::new;
    }

    // Was unable to create matching Map constructor
    return null;
  }

  private <T> ObjectConstructor<T> newUnsafeAllocator(Class<? super T> rawType) {
    if (useJdkUnsafe) {
      return () -> {
        try {
          @SuppressWarnings("unchecked")
          T newInstance = (T) UnsafeAllocator.INSTANCE.newInstance(rawType);
          return newInstance;
        } catch (Exception e) {
          throw new RuntimeException(
              ("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."),
              e);
        }
      };
    } else {
      String exceptionMessage =
          "Unable to create instance of "
              + rawType
              + "; usage of JDK Unsafe is disabled. Registering an InstanceCreator or a TypeAdapter"
              + " for this type, adding a no-args constructor, or enabling usage of JDK Unsafe may"
              + " fix this problem.";

      // Check if R8 removed all constructors
      if (rawType.getDeclaredConstructors().length == 0) {
        // R8 with Unsafe disabled might not be common enough to warrant a separate Troubleshooting

View on GitHub (pinned to 310ac341f2)

Solutions

  1. Add a no-args constructor to the class so Gson doesn't need Unsafe
  2. Register an InstanceCreator for the type to control construction
  3. Register a custom TypeAdapter for the type
  4. If on JDK 16+, add --add-opens java.base/sun.misc=ALL-UNNAMED (less safe) or migrate to explicit constructors

Example fix

// before
class Foo {
  public Foo(String x) {} // only ctor, no no-args
}

// after
class Foo {
  public Foo() {}        // Gson uses this
  public Foo(String x) {}
}
Defensive patterns

Strategy: validation

Validate before calling

// Verify a no-args constructor exists before relying on Unsafe fallback
Class<?> c = MyType.class;
try {
  c.getDeclaredConstructor();
} catch (NoSuchMethodException e) {
  // Unsafe will be attempted; register InstanceCreator to avoid fragility
  gsonBuilder.registerTypeAdapter(c, (InstanceCreator<MyType>) t -> new MyType(defaultArg));
}

Try / catch

try {
  return gson.fromJson(json, MyType.class);
} catch (RuntimeException e) {
  if (e.getMessage() != null && e.getMessage().startsWith("Unable to create instance")) {
    // Unsafe failed; provide InstanceCreator and retry
    throw new MyParseException("Unsafe allocation failed for " + MyType.class, e);
  }
  throw e;
}

Prevention

When it happens

Trigger: 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.

Common situations: Android runtimes without sun.misc.Unsafe; JDK 16+ where sun.misc.Unsafe access is restricted; exotic JVMs; classes Unsafe refuses to instantiate (arrays, primitives).

Related errors


AI-assisted analysis of google/gson@310ac341f2 (2026-08-10). Data as JSON: /api/errors/be14fc6abec34743. Report an issue: GitHub.