Refuse kotlin classes in ClassJsonAdapter (#749)

* Refuse kotlin classes in ClassJsonAdapter

* Fail()

* Tweak message
This commit is contained in:
Zac Sweers
2018-11-19 23:36:52 -08:00
committed by GitHub
parent 4550da0abe
commit c64138bf0a
2 changed files with 20 additions and 0 deletions

View File

@@ -952,4 +952,16 @@ class KotlinJsonAdapterTest {
assertThat(adapter.fromJson("null")).isNull() assertThat(adapter.fromJson("null")).isNull()
assertThat(adapter.toJson(null)).isEqualTo("null") assertThat(adapter.toJson(null)).isEqualTo("null")
} }
@Test fun kotlinClassesWithoutAdapterAreRefused() {
val moshi = Moshi.Builder().build()
try {
moshi.adapter<PlainKotlinClass>(PlainKotlinClass::class.java)
fail("Should not pass here")
} catch (e: IllegalArgumentException) {
assertThat(e).hasMessageContaining("Reflective serialization of Kotlin classes")
}
}
class PlainKotlinClass
} }

View File

@@ -75,6 +75,14 @@ final class ClassJsonAdapter<T> extends JsonAdapter<T> {
if (Modifier.isAbstract(rawType.getModifiers())) { if (Modifier.isAbstract(rawType.getModifiers())) {
throw new IllegalArgumentException("Cannot serialize abstract class " + rawType.getName()); throw new IllegalArgumentException("Cannot serialize abstract class " + rawType.getName());
} }
for (Annotation annotation : rawType.getDeclaredAnnotations()) {
if ("kotlin.Metadata".equals(annotation.annotationType().getName())) {
throw new IllegalArgumentException("Cannot serialize Kotlin type " + rawType.getName()
+ ". Reflective serialization of Kotlin classes without using kotlin-reflect has "
+ "undefined and unexpected behavior. Please use KotlinJsonAdapter from the "
+ "moshi-kotlin artifact or use code gen from the moshi-kotlin-codegen artifact.");
}
}
ClassFactory<Object> classFactory = ClassFactory.get(rawType); ClassFactory<Object> classFactory = ClassFactory.get(rawType);
Map<String, FieldBinding<?>> fields = new TreeMap<>(); Map<String, FieldBinding<?>> fields = new TreeMap<>();