diff --git a/gson/src/main/java/com/google/gson/Gson.java b/gson/src/main/java/com/google/gson/Gson.java index 5feebb7bf6..0ed8028715 100644 --- a/gson/src/main/java/com/google/gson/Gson.java +++ b/gson/src/main/java/com/google/gson/Gson.java @@ -22,11 +22,13 @@ import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.Excluder; import com.google.gson.internal.GsonBuildConfig; +import com.google.gson.internal.GsonInternalAccess; import com.google.gson.internal.Primitives; import com.google.gson.internal.Streams; import com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory; import com.google.gson.internal.bind.JsonTreeReader; import com.google.gson.internal.bind.JsonTreeWriter; +import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory; import com.google.gson.internal.bind.SerializationDelegatingTypeAdapter; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; @@ -201,6 +203,17 @@ public final class Gson { final ToNumberStrategy numberToNumberStrategy; final List reflectionFilters; + static { + GsonInternalAccess.INSTANCE = + new GsonInternalAccess() { + @Override + public TypeAdapter getOptionallyReflectiveAdapter( + Gson gson, TypeToken type, boolean allowReflective) { + return gson.getOptionallyReflectiveAdapter(type, allowReflective); + } + }; + } + /** * Constructs a Gson object with default configuration. The default configuration has the * following settings: @@ -408,6 +421,91 @@ public TypeAdapter getAdapter(Class type) { return getAdapter(TypeToken.get(type)); } + /** + * Returns the type adapter the factory lookup would select for {@code type}, as far as it is not + * created by reflection. This is used by {@code TypeAdapterRuntimeTypeWrapper}, which discards + * the reflective adapter for the runtime type when the adapter for the declared type does not use + * reflection; in that situation the reflective adapter should not be created at all, so that its + * creation failure does not escape even though the adapter would have been discarded anyway. See + * https://github.com/google/gson/issues/3122. + * + *

Adapters created by factories before {@link ReflectiveTypeAdapterFactory} are returned + * normally, including caching; failures of those factories propagate unchanged. If only the + * reflective factory could handle {@code type}, this method returns {@code null} when {@code + * allowReflective} is false, and otherwise behaves like {@link #getAdapter(TypeToken)}. + */ + TypeAdapter getOptionallyReflectiveAdapter(TypeToken type, boolean allowReflective) { + if (allowReflective) { + return getAdapter(type); + } + + TypeAdapter cached = typeTokenCache.get(type); + if (cached != null) { + if (cached instanceof ReflectiveTypeAdapterFactory.Adapter) { + return null; + } + @SuppressWarnings("unchecked") + TypeAdapter adapter = (TypeAdapter) cached; + return adapter; + } + + Map, TypeAdapter> threadCalls = threadLocalAdapterResults.get(); + boolean isInitialAdapterRequest = false; + if (threadCalls == null) { + threadCalls = new HashMap<>(); + threadLocalAdapterResults.set(threadCalls); + isInitialAdapterRequest = true; + } else { + // the key and value type parameters always agree + @SuppressWarnings("unchecked") + TypeAdapter ongoingCall = (TypeAdapter) threadCalls.get(type); + if (ongoingCall != null) { + return ongoingCall; + } + } + + TypeAdapter candidate = null; + try { + FutureTypeAdapter call = new FutureTypeAdapter<>(); + threadCalls.put(type, call); + + for (TypeAdapterFactory factory : factories) { + // The reflective adapter is the last resort; skip creating it when the caller discards it + // anyway + if (factory instanceof ReflectiveTypeAdapterFactory) { + return null; + } + candidate = factory.create(this, type); + if (candidate != null) { + call.setDelegate(candidate); + // Replace future adapter with actual adapter + threadCalls.put(type, candidate); + break; + } + } + } finally { + if (isInitialAdapterRequest) { + threadLocalAdapterResults.remove(); + } + } + + if (candidate == null) { + throw new IllegalArgumentException( + "Gson (" + GsonBuildConfig.VERSION + ") cannot handle " + type); + } + + if (isInitialAdapterRequest) { + /* + * Publish resolved adapters to all threads + * Can only do this for the initial request because cyclic dependency TypeA -> TypeB -> TypeA + * would otherwise publish adapter for TypeB which uses not yet resolved adapter for TypeA + * See https://github.com/google/gson/issues/625 + */ + typeTokenCache.putAll(threadCalls); + } + return candidate; + } + /** * This method is used to get an alternate type adapter for the specified type. This is used to * access a type adapter that is overridden by a {@link TypeAdapterFactory} that you may have diff --git a/gson/src/main/java/com/google/gson/internal/GsonInternalAccess.java b/gson/src/main/java/com/google/gson/internal/GsonInternalAccess.java new file mode 100644 index 0000000000..7375e3f252 --- /dev/null +++ b/gson/src/main/java/com/google/gson/internal/GsonInternalAccess.java @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2026 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.gson.internal; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.reflect.TypeToken; + +/** Internal-only APIs of Gson available only to other classes in Gson. */ +public abstract class GsonInternalAccess { + // Suppress warnings because field is initialized by `Gson` class during class loading + // (and therefore should be thread-safe), and any usage appears after `Gson` was loaded + @SuppressWarnings({"ConstantField", "NonFinalStaticField"}) + public static volatile GsonInternalAccess INSTANCE; + + /** + * Returns the type adapter the factory lookup would select for {@code type}, as far as it is not + * created by reflection. + * + *

Adapters created by factories before the reflective factory are returned normally, with the + * usual caching, and failures of those factories propagate unchanged. If only the reflective + * factory could handle {@code type}, then: + * + *

    + *
  • With {@code allowReflective == false} this method returns {@code null} without creating + * the reflective adapter, so the caller can fall back to the adapter for the declared type + * and creation failures of the reflective adapter are not triggered needlessly. + *
  • With {@code allowReflective == true} the reflective adapter is created and returned, and + * its creation failures propagate; this behaves like {@link Gson#getAdapter(TypeToken)}. + *
+ */ + public abstract TypeAdapter getOptionallyReflectiveAdapter( + Gson gson, TypeToken type, boolean allowReflective); +} diff --git a/gson/src/main/java/com/google/gson/internal/bind/TypeAdapterRuntimeTypeWrapper.java b/gson/src/main/java/com/google/gson/internal/bind/TypeAdapterRuntimeTypeWrapper.java index 6c6e82e2ad..f98cd29c31 100644 --- a/gson/src/main/java/com/google/gson/internal/bind/TypeAdapterRuntimeTypeWrapper.java +++ b/gson/src/main/java/com/google/gson/internal/bind/TypeAdapterRuntimeTypeWrapper.java @@ -17,6 +17,7 @@ import com.google.gson.Gson; import com.google.gson.TypeAdapter; +import com.google.gson.internal.GsonInternalAccess; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -56,22 +57,23 @@ public void write(JsonWriter out, T value) throws IOException { @SuppressWarnings("ReferenceEquality") boolean isDifferentType = runtimeType != type; if (isDifferentType) { - @SuppressWarnings("unchecked") - TypeAdapter runtimeTypeAdapter = - (TypeAdapter) context.getAdapter(TypeToken.get(runtimeType)); // For backward compatibility only check ReflectiveTypeAdapterFactory.Adapter here but not any // other wrapping adapters, see // https://github.com/google/gson/pull/1787#issuecomment-1222175189 - if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) { - // The user registered a type adapter for the runtime type, so we will use that + boolean allowReflective = isReflective(delegate); + // Look up the adapter for the runtime type without creating a reflective one unless it would + // actually be used, see https://github.com/google/gson/issues/3122 + @SuppressWarnings("unchecked") + TypeToken runtimeTypeToken = (TypeToken) TypeToken.get(runtimeType); + TypeAdapter runtimeTypeAdapter = + GsonInternalAccess.INSTANCE.getOptionallyReflectiveAdapter( + context, runtimeTypeToken, allowReflective); + if (runtimeTypeAdapter != null) { chosen = runtimeTypeAdapter; - } else if (!isReflective(delegate)) { - // The user registered a type adapter for Base class, so we prefer it over the - // reflective type adapter for the runtime type - chosen = delegate; } else { - // Use the type adapter for runtime type - chosen = runtimeTypeAdapter; + // The adapter for the declared type does not use reflection, but only a reflective adapter + // could be created for the runtime type, so keep the former + chosen = delegate; } } chosen.write(out, value); diff --git a/gson/src/test/java/com/google/gson/functional/TypeAdapterRuntimeTypeWrapperTest.java b/gson/src/test/java/com/google/gson/functional/TypeAdapterRuntimeTypeWrapperTest.java index 82fe45ff6a..f5b1f8bec0 100644 --- a/gson/src/test/java/com/google/gson/functional/TypeAdapterRuntimeTypeWrapperTest.java +++ b/gson/src/test/java/com/google/gson/functional/TypeAdapterRuntimeTypeWrapperTest.java @@ -17,19 +17,27 @@ package com.google.gson.functional; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertThrows; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; +import com.google.gson.JsonIOException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; +import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; +import java.util.Arrays; +import java.util.List; import org.junit.Test; public class TypeAdapterRuntimeTypeWrapperTest { @@ -202,4 +210,122 @@ public void testGsonFutureAdapter() { String json = new Gson().toJson(b); assertThat(json).isEqualTo("{\"f\":{\"i\":2}}"); } + + /** + * The runtime class of the {@link WildcardType} instances created by the JDK's reflection APIs. + * It is an internal JDK class whose fields Gson cannot make accessible, see + * https://github.com/google/gson/issues/3122. + */ + private static final String WILDCARD_TYPE_IMPL_CLASS_NAME = + "sun.reflect.generics.reflectiveObjects.WildcardTypeImpl"; + + /** A trivial adapter for {@link WildcardType} which never uses reflection. */ + private static final TypeAdapter WILDCARD_ADAPTER = + new TypeAdapter() { + @Override + public void write(JsonWriter out, WildcardType value) throws IOException { + out.value(value == null ? null : value.getTypeName()); + } + + @Override + public WildcardType read(JsonReader in) throws IOException { + String ignored = in.nextString(); + return null; + } + }; + + private static class WildcardTypeHolder { + @SuppressWarnings("unused") + List field; + } + + private static WildcardType createWildcardType() throws Exception { + ParameterizedType listOfWildcard = + (ParameterizedType) WildcardTypeHolder.class.getDeclaredField("field").getGenericType(); + return (WildcardType) listOfWildcard.getActualTypeArguments()[0]; + } + + /** + * Registering an adapter for the declared type should also be sufficient to serialize values + * inside arrays, even when the runtime class is a JDK-internal class which Gson cannot reflect + * over. The reflective adapter for the runtime type is only the third preference and would be + * discarded anyway, so its creation failure must not escape. See + * https://github.com/google/gson/issues/3122. + */ + @Test + public void testCustomAdapterForDeclaredTypeUsedForArrayElements() throws Exception { + WildcardType wildcard = createWildcardType(); + assertThat(wildcard.getClass().getName()).isEqualTo(WILDCARD_TYPE_IMPL_CLASS_NAME); + Gson gson = + new GsonBuilder().registerTypeAdapter(WildcardType.class, WILDCARD_ADAPTER).create(); + + WildcardType[] array = new WildcardType[] {wildcard}; + assertThat(gson.toJson(wildcard, WildcardType.class)) + .isEqualTo("\"? extends java.lang.Number\""); + assertThat(gson.toJson(array, WildcardType[].class)) + .isEqualTo("[\"? extends java.lang.Number\"]"); + } + + /** + * Same as {@code testCustomAdapterForDeclaredTypeUsedForArrayElements}, but for the elements of a + * collection. See https://github.com/google/gson/issues/3122. + */ + @Test + public void testCustomAdapterForDeclaredTypeUsedForCollectionElements() throws Exception { + WildcardType wildcard = createWildcardType(); + Gson gson = + new GsonBuilder().registerTypeAdapter(WildcardType.class, WILDCARD_ADAPTER).create(); + + List list = Arrays.asList(wildcard); + Type listType = new TypeToken>() {}.getType(); + assertThat(gson.toJson(list, listType)).isEqualTo("[\"? extends java.lang.Number\"]"); + } + + /** + * A failure of a user-registered factory for the runtime type must not be silently swallowed: + * that factory's adapter would have been the first preference, so its error has to propagate. + */ + @Test + public void testUserFactoryFailureForRuntimeTypePropagates() throws Exception { + Class wildcardImplClass = Class.forName(WILDCARD_TYPE_IMPL_CLASS_NAME); + TypeAdapterFactory failingFactory = + new TypeAdapterFactory() { + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (type.getRawType() == wildcardImplClass) { + throw new IllegalStateException("user factory failed"); + } + return null; + } + }; + + Gson gson = + new GsonBuilder() + .registerTypeAdapterFactory(failingFactory) + .registerTypeAdapter(WildcardType.class, WILDCARD_ADAPTER) + .create(); + + List list = Arrays.asList(createWildcardType()); + Type listType = new TypeToken>() {}.getType(); + IllegalStateException e = + assertThrows(IllegalStateException.class, () -> gson.toJson(list, listType)); + assertThat(e).hasMessageThat().isEqualTo("user factory failed"); + } + + /** + * When the delegate is reflective, the reflective adapter for the runtime type is the preferred + * adapter, so its creation failure must keep failing fast. + */ + @Test + public void testReflectiveCreationFailureStillPropagatesWhenDelegateIsReflective() + throws Exception { + WildcardType wildcard = createWildcardType(); + Gson gson = new Gson(); + + WildcardType[] array = new WildcardType[] {wildcard}; + List list = Arrays.asList(wildcard); + Type listType = new TypeToken>() {}.getType(); + assertThrows(JsonIOException.class, () -> gson.toJson(array, WildcardType[].class)); + assertThrows(JsonIOException.class, () -> gson.toJson(list, listType)); + } }