-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Fix TypeAdapterRuntimeTypeWrapper not detecting reflective TreeTypeAdapter and FutureTypeAdapter #1787
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
eamonnmcmanus
merged 8 commits into
google:master
from
Marcono1234:marcono1234/TypeAdapterRuntimeTypeWrapper-not-detecting-reflective-TreeTypeAdapter
Oct 10, 2022
Merged
Fix TypeAdapterRuntimeTypeWrapper not detecting reflective TreeTypeAdapter and FutureTypeAdapter #1787
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
764286a
Fix TypeAdapterRuntimeTypeWrapper not detecting reflective TreeTypeAd…
Marcono1234 5be9071
Merge branch 'master' into marcono1234/TypeAdapterRuntimeTypeWrapper-…
Marcono1234 767c10e
Address review feedback
Marcono1234 3d2b33a
Merge branch 'master' into marcono1234/TypeAdapterRuntimeTypeWrapper-…
Marcono1234 f980e6d
Convert TypeAdapterRuntimeTypeWrapperTest to JUnit 4 test
Marcono1234 eb96663
Prefer wrapped reflective adapter for serialization of subclass
Marcono1234 dd199e8
Detect reflective adapter used as delegate for Gson.FutureTypeAdapter
Marcono1234 aeda2bd
Tiny style tweak.
eamonnmcmanus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
gson/src/main/java/com/google/gson/internal/bind/SerializationDelegatingTypeAdapter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
package com.google.gson.internal.bind; | ||
|
||
import com.google.gson.TypeAdapter; | ||
|
||
/** | ||
* Type adapter which might delegate serialization to another adapter. | ||
*/ | ||
public abstract class SerializationDelegatingTypeAdapter<T> extends TypeAdapter<T> { | ||
/** | ||
* Returns the adapter used for serialization, might be {@code this} or another adapter. | ||
* That other adapter might itself also be a {@code SerializationDelegatingTypeAdapter}. | ||
*/ | ||
public abstract TypeAdapter<T> getSerializationDelegate(); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -53,10 +53,12 @@ public void write(JsonWriter out, T value) throws IOException { | |
if (runtimeType != type) { | ||
@SuppressWarnings("unchecked") | ||
TypeAdapter<T> runtimeTypeAdapter = (TypeAdapter<T>) 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 | ||
chosen = runtimeTypeAdapter; | ||
} else if (!(delegate instanceof ReflectiveTypeAdapterFactory.Adapter)) { | ||
} 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; | ||
|
@@ -68,12 +70,30 @@ public void write(JsonWriter out, T value) throws IOException { | |
chosen.write(out, value); | ||
} | ||
|
||
/** | ||
* Returns whether the type adapter uses reflection. | ||
* | ||
* @param typeAdapter the type adapter to check. | ||
*/ | ||
private static boolean isReflective(TypeAdapter<?> typeAdapter) { | ||
// Run this in loop in case multiple delegating adapters are nested | ||
while (typeAdapter instanceof SerializationDelegatingTypeAdapter) { | ||
TypeAdapter<?> delegate = ((SerializationDelegatingTypeAdapter<?>) typeAdapter).getSerializationDelegate(); | ||
// Break if adapter does not delegate serialization | ||
if (delegate == typeAdapter) { | ||
break; | ||
} | ||
typeAdapter = delegate; | ||
} | ||
|
||
return typeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter; | ||
} | ||
|
||
/** | ||
* Finds a compatible runtime type if it is more specific | ||
*/ | ||
private Type getRuntimeTypeIfMoreSpecific(Type type, Object value) { | ||
if (value != null | ||
&& (type == Object.class || type instanceof TypeVariable<?> || type instanceof Class<?>)) { | ||
private static Type getRuntimeTypeIfMoreSpecific(Type type, Object value) { | ||
if (value != null && (type instanceof Class<?> || type instanceof TypeVariable<?>)) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Note: Simplified this because |
||
type = value.getClass(); | ||
} | ||
return type; | ||
|
193 changes: 193 additions & 0 deletions
193
gson/src/test/java/com/google/gson/functional/TypeAdapterRuntimeTypeWrapperTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,193 @@ | ||
package com.google.gson.functional; | ||
|
||
import static org.junit.Assert.assertEquals; | ||
|
||
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.JsonPrimitive; | ||
import com.google.gson.JsonSerializationContext; | ||
import com.google.gson.JsonSerializer; | ||
import com.google.gson.TypeAdapter; | ||
import com.google.gson.stream.JsonReader; | ||
import com.google.gson.stream.JsonWriter; | ||
import java.io.IOException; | ||
import java.lang.reflect.Type; | ||
import org.junit.Test; | ||
|
||
public class TypeAdapterRuntimeTypeWrapperTest { | ||
private static class Base { | ||
} | ||
private static class Subclass extends Base { | ||
@SuppressWarnings("unused") | ||
String f = "test"; | ||
} | ||
private static class Container { | ||
@SuppressWarnings("unused") | ||
Base b = new Subclass(); | ||
} | ||
private static class Deserializer implements JsonDeserializer<Base> { | ||
@Override | ||
public Base deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { | ||
throw new AssertionError("not needed for this test"); | ||
} | ||
} | ||
|
||
/** | ||
* When custom {@link JsonSerializer} is registered for Base should | ||
* prefer that over reflective adapter for Subclass for serialization. | ||
*/ | ||
@Test | ||
public void testJsonSerializer() { | ||
Gson gson = new GsonBuilder() | ||
.registerTypeAdapter(Base.class, new JsonSerializer<Base>() { | ||
@Override | ||
public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) { | ||
return new JsonPrimitive("serializer"); | ||
} | ||
}) | ||
.create(); | ||
|
||
String json = gson.toJson(new Container()); | ||
assertEquals("{\"b\":\"serializer\"}", json); | ||
} | ||
|
||
/** | ||
* When only {@link JsonDeserializer} is registered for Base, then on | ||
* serialization should prefer reflective adapter for Subclass since | ||
* Base would use reflective adapter as delegate. | ||
*/ | ||
@Test | ||
public void testJsonDeserializer_ReflectiveSerializerDelegate() { | ||
Gson gson = new GsonBuilder() | ||
.registerTypeAdapter(Base.class, new Deserializer()) | ||
.create(); | ||
|
||
String json = gson.toJson(new Container()); | ||
assertEquals("{\"b\":{\"f\":\"test\"}}", json); | ||
} | ||
|
||
/** | ||
* When {@link JsonDeserializer} with custom adapter as delegate is | ||
* registered for Base, then on serialization should prefer custom adapter | ||
* delegate for Base over reflective adapter for Subclass. | ||
*/ | ||
@Test | ||
public void testJsonDeserializer_CustomSerializerDelegate() { | ||
Gson gson = new GsonBuilder() | ||
// Register custom delegate | ||
.registerTypeAdapter(Base.class, new TypeAdapter<Base>() { | ||
@Override | ||
public Base read(JsonReader in) throws IOException { | ||
throw new UnsupportedOperationException(); | ||
} | ||
@Override | ||
public void write(JsonWriter out, Base value) throws IOException { | ||
out.value("custom delegate"); | ||
} | ||
}) | ||
.registerTypeAdapter(Base.class, new Deserializer()) | ||
.create(); | ||
|
||
String json = gson.toJson(new Container()); | ||
assertEquals("{\"b\":\"custom delegate\"}", json); | ||
} | ||
|
||
/** | ||
* When two (or more) {@link JsonDeserializer}s are registered for Base | ||
* which eventually fall back to reflective adapter as delegate, then on | ||
* serialization should prefer reflective adapter for Subclass. | ||
*/ | ||
@Test | ||
public void testJsonDeserializer_ReflectiveTreeSerializerDelegate() { | ||
Gson gson = new GsonBuilder() | ||
// Register delegate which itself falls back to reflective serialization | ||
.registerTypeAdapter(Base.class, new Deserializer()) | ||
.registerTypeAdapter(Base.class, new Deserializer()) | ||
.create(); | ||
|
||
String json = gson.toJson(new Container()); | ||
assertEquals("{\"b\":{\"f\":\"test\"}}", json); | ||
} | ||
|
||
/** | ||
* When {@link JsonDeserializer} with {@link JsonSerializer} as delegate | ||
* is registered for Base, then on serialization should prefer | ||
* {@code JsonSerializer} over reflective adapter for Subclass. | ||
*/ | ||
@Test | ||
public void testJsonDeserializer_JsonSerializerDelegate() { | ||
Gson gson = new GsonBuilder() | ||
// Register JsonSerializer as delegate | ||
.registerTypeAdapter(Base.class, new JsonSerializer<Base>() { | ||
@Override | ||
public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) { | ||
return new JsonPrimitive("custom delegate"); | ||
} | ||
}) | ||
.registerTypeAdapter(Base.class, new Deserializer()) | ||
.create(); | ||
|
||
String json = gson.toJson(new Container()); | ||
assertEquals("{\"b\":\"custom delegate\"}", json); | ||
} | ||
|
||
/** | ||
* When a {@link JsonDeserializer} is registered for Subclass, and a custom | ||
* {@link JsonSerializer} is registered for Base, then Gson should prefer | ||
* the reflective adapter for Subclass for backward compatibility (see | ||
* https://github.com/google/gson/pull/1787#issuecomment-1222175189) even | ||
* though normally TypeAdapterRuntimeTypeWrapper should prefer the custom | ||
* serializer for Base. | ||
*/ | ||
@Test | ||
public void testJsonDeserializer_SubclassBackwardCompatibility() { | ||
Gson gson = new GsonBuilder() | ||
.registerTypeAdapter(Subclass.class, new JsonDeserializer<Subclass>() { | ||
@Override | ||
public Subclass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { | ||
throw new AssertionError("not needed for this test"); | ||
} | ||
}) | ||
.registerTypeAdapter(Base.class, new JsonSerializer<Base>() { | ||
@Override | ||
public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) { | ||
return new JsonPrimitive("base"); | ||
} | ||
}) | ||
.create(); | ||
|
||
String json = gson.toJson(new Container()); | ||
assertEquals("{\"b\":{\"f\":\"test\"}}", json); | ||
} | ||
|
||
private static class CyclicBase { | ||
@SuppressWarnings("unused") | ||
CyclicBase f; | ||
} | ||
|
||
private static class CyclicSub extends CyclicBase { | ||
@SuppressWarnings("unused") | ||
int i; | ||
|
||
public CyclicSub(int i) { | ||
this.i = i; | ||
} | ||
} | ||
|
||
/** | ||
* Tests behavior when the type of a field refers to a type whose adapter is | ||
* currently in the process of being created. For these cases {@link Gson} | ||
* uses a future adapter for the type. That adapter later uses the actual | ||
* adapter as delegate. | ||
*/ | ||
@Test | ||
public void testGsonFutureAdapter() { | ||
CyclicBase b = new CyclicBase(); | ||
b.f = new CyclicSub(2); | ||
String json = new Gson().toJson(b); | ||
assertEquals("{\"f\":{\"i\":2}}", json); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.