Skip to content

Commit

Permalink
Kotlin: Improve KotlinSerializerCodec (#1152)
Browse files Browse the repository at this point in the history
Only support classes annotated as serializable.

JAVA-5035
  • Loading branch information
rozza authored Jun 23, 2023
1 parent 63af01b commit 6b6c3dd
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ package org.bson.codecs.kotlinx
import kotlin.reflect.KClass
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.findAnnotations
import kotlin.reflect.full.hasAnnotation
import kotlin.reflect.full.primaryConstructor
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.InternalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.serializer
Expand Down Expand Up @@ -85,14 +87,14 @@ private constructor(
serializersModule: SerializersModule = defaultSerializersModule,
bsonConfiguration: BsonConfiguration = BsonConfiguration()
): Codec<T>? {
return if (!(kClass.isData || kClass.isValue || kClass.isSealed)) {
null
} else {
return if (kClass.hasAnnotation<Serializable>()) {
try {
create(kClass, kClass.serializer(), serializersModule, bsonConfiguration)
} catch (exception: SerializationException) {
null
}
} else {
null
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class KotlinSerializerCodecProviderTest {
@Test
fun shouldReturnNullForNonSerializableClass() {
assertNull(KotlinSerializerCodecProvider().get(NotMarkedSerializable::class.java, Bson.DEFAULT_CODEC_REGISTRY))
assertNull(KotlinSerializerCodecProvider().get(DoubleArray::class.java, Bson.DEFAULT_CODEC_REGISTRY))
assertNull(KotlinSerializerCodecProvider().get(CharSequence::class.java, Bson.DEFAULT_CODEC_REGISTRY))
}

@Test
Expand All @@ -50,12 +52,6 @@ class KotlinSerializerCodecProviderTest {
assertNull(codec)
}

@Test
fun shouldReturnNullForSerializableButNotValueClassOrSealedOrDataClassTypes() {
assertNull(KotlinSerializerCodecProvider().get(DoubleArray::class.java, Bson.DEFAULT_CODEC_REGISTRY))
assertNull(KotlinSerializerCodecProvider().get(CharSequence::class.java, Bson.DEFAULT_CODEC_REGISTRY))
}

@Test
fun shouldReturnKotlinSerializerCodecUsingDefaultRegistry() {
val codec = MongoClientSettings.getDefaultCodecRegistry().get(DataClassWithSimpleValues::class.java)
Expand Down

0 comments on commit 6b6c3dd

Please sign in to comment.