Skip to content
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

Fix error message when missing primary constructor. #1840

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1074,6 +1074,24 @@ class KotlinJsonAdapterTest {

sealed class SealedClass

@Test fun requirePrimaryConstructor() {
val moshi: Moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
try {
moshi.adapter(SubClass::class.java)
} catch (e: IllegalArgumentException) {
assertThat(e).hasMessageThat()
.contains("Cannot reflectively serialize class without the primary constructor")
}
}

open class SuperClass

class SubClass : SuperClass {
constructor() : super()
}

private fun <T> mapWildcardsParameterizedTest(type: Class<T>, json: String, value: T) {
// Ensure the map was created with the expected wildcards of a Kotlin map.
val fieldType = type.getDeclaredField("map").genericType
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,9 @@ public class KotlinJsonAdapterFactory : JsonAdapter.Factory {
// Fall back to a reflective adapter when the generated adapter is not found.
}

require(!rawType.isAnonymousClass) {
"Cannot serialize anonymous class ${rawType.name}"
}
require(!rawType.isLocalClass) {
"Cannot serialize local class or object expression ${rawType.name}"
}
Expand All @@ -230,7 +233,11 @@ public class KotlinJsonAdapterFactory : JsonAdapter.Factory {
"Cannot reflectively serialize sealed class ${rawType.name}. Please register an adapter."
}

val constructor = rawTypeKotlin.primaryConstructor ?: return null
val constructor = rawTypeKotlin.primaryConstructor
requireNotNull(constructor) {
"Cannot reflectively serialize class without the primary constructor ${rawType.name}." +
" Please register an adapter."
}
val parametersByName = constructor.parameters.associateBy { it.name }
constructor.isAccessible = true

Expand Down