Don't handle WildcardTypes in ClassJsonAdapter. (#406)

This commit is contained in:
Eric Cochran
2018-01-07 11:05:49 -08:00
committed by Jesse Wilson
parent 0a6e836762
commit a210d89a55
2 changed files with 23 additions and 2 deletions

View File

@@ -45,7 +45,8 @@ final class ClassJsonAdapter<T> extends JsonAdapter<T> {
public static final JsonAdapter.Factory FACTORY = new JsonAdapter.Factory() { public static final JsonAdapter.Factory FACTORY = new JsonAdapter.Factory() {
@Override public @Nullable JsonAdapter<?> create( @Override public @Nullable JsonAdapter<?> create(
Type type, Set<? extends Annotation> annotations, Moshi moshi) { Type type, Set<? extends Annotation> annotations, Moshi moshi) {
Class<?> rawType = Types.getRawType(type); if (!(type instanceof Class)) return null;
Class<?> rawType = (Class<?>) type;
if (rawType.isInterface() || rawType.isEnum()) return null; if (rawType.isInterface() || rawType.isEnum()) return null;
if (isPlatformType(rawType) && !Types.isAllowedPlatformType(rawType)) { if (isPlatformType(rawType) && !Types.isAllowedPlatformType(rawType)) {
throw new IllegalArgumentException("Platform " throw new IllegalArgumentException("Platform "
@@ -71,7 +72,7 @@ final class ClassJsonAdapter<T> extends JsonAdapter<T> {
ClassFactory<Object> classFactory = ClassFactory.get(rawType); ClassFactory<Object> classFactory = ClassFactory.get(rawType);
Map<String, FieldBinding<?>> fields = new TreeMap<>(); Map<String, FieldBinding<?>> fields = new TreeMap<>();
for (Type t = type; t != Object.class; t = Types.getGenericSuperclass(t)) { for (Type t = rawType; t != Object.class; t = Types.getGenericSuperclass(t)) {
createFieldBindings(moshi, t, fields); createFieldBindings(moshi, t, fields);
} }
return new ClassJsonAdapter<>(classFactory, fields).nullSafe(); return new ClassJsonAdapter<>(classFactory, fields).nullSafe();

View File

@@ -534,6 +534,26 @@ public final class MoshiTest {
assertThat(adapter.toJson(null)).isEqualTo("null"); assertThat(adapter.toJson(null)).isEqualTo("null");
} }
@Test public void upperBoundedWildcardsAreNotHandled() {
Moshi moshi = new Moshi.Builder().build();
try {
moshi.adapter(Types.subtypeOf(String.class));
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("No JsonAdapter for ? extends java.lang.String annotated []");
}
}
@Test public void lowerBoundedWildcardsAreNotHandled() {
Moshi moshi = new Moshi.Builder().build();
try {
moshi.adapter(Types.supertypeOf(String.class));
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("No JsonAdapter for ? super java.lang.String annotated []");
}
}
@Test public void addNullFails() throws Exception { @Test public void addNullFails() throws Exception {
Type type = Object.class; Type type = Object.class;
Class<? extends Annotation> annotation = Annotation.class; Class<? extends Annotation> annotation = Annotation.class;