/
SerializersJvm.kt
177 lines (165 loc) · 8.85 KB
/
SerializersJvm.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:JvmMultifileClass
@file:JvmName("SerializersKt")
@file:Suppress("UNCHECKED_CAST")
package kotlinx.serialization
import kotlinx.serialization.builtins.*
import kotlinx.serialization.builtins.MapEntrySerializer
import kotlinx.serialization.builtins.PairSerializer
import kotlinx.serialization.builtins.TripleSerializer
import kotlinx.serialization.internal.*
import kotlinx.serialization.modules.*
import java.lang.reflect.*
import kotlin.reflect.*
/**
* Reflectively constructs a serializer for the given reflective Java [type].
* [serializer] is intended to be used as an interoperability layer for libraries like GSON and Retrofit,
* that operate with reflective Java [Type] and cannot use [typeOf].
*
* For application-level serialization, it is recommended to use `serializer<T>()` instead as it is aware of
* Kotlin-specific type information, such as nullability, sealed classes and object singletons.
*
* @throws SerializationException if serializer cannot be created (provided [type] or its type argument is not serializable).
*/
@ExperimentalSerializationApi
public fun serializer(type: Type): KSerializer<Any> = EmptySerializersModule.serializer(type)
/**
* Reflectively constructs a serializer for the given reflective Java [type].
* [serializer] is intended to be used as an interoperability layer for libraries like GSON and Retrofit,
* that operate with reflective Java [Type] and cannot use [typeOf].
*
* For application-level serialization, it is recommended to use `serializer<T>()` instead as it is aware of
* Kotlin-specific type information, such as nullability, sealed classes and object singletons.
*
* Returns `null` if serializer cannot be created (provided [type] or its type argument is not serializable).
*/
@ExperimentalSerializationApi
public fun serializerOrNull(type: Type): KSerializer<Any>? = EmptySerializersModule.serializerOrNull(type)
/**
* Retrieves serializer for the given reflective Java [type] using
* reflective construction and [contextual][SerializersModule.getContextual] lookup for non-serializable types.
*
* [serializer] is intended to be used as an interoperability layer for libraries like GSON and Retrofit,
* that operate with reflective Java [Type] and cannot use [typeOf].
*
* For application-level serialization, it is recommended to use `serializer<T>()` instead as it is aware of
* Kotlin-specific type information, such as nullability, sealed classes and object singletons.
*
* @throws SerializationException if serializer cannot be created (provided [type] or its type argument is not serializable).
*/
@ExperimentalSerializationApi
public fun SerializersModule.serializer(type: Type): KSerializer<Any> =
serializerByJavaTypeImpl(type, failOnMissingTypeArgSerializer = true) ?: type.kclass().serializerNotRegistered()
/**
* Retrieves serializer for the given reflective Java [type] using
* reflective construction and [contextual][SerializersModule.getContextual] lookup for non-serializable types.
*
* [serializer] is intended to be used as an interoperability layer for libraries like GSON and Retrofit,
* that operate with reflective Java [Type] and cannot use [typeOf].
*
* For application-level serialization, it is recommended to use `serializer<T>()` instead as it is aware of
* Kotlin-specific type information, such as nullability, sealed classes and object singletons.
*
* Returns `null` if serializer cannot be created (provided [type] or its type argument is not serializable).
*/
@ExperimentalSerializationApi
public fun SerializersModule.serializerOrNull(type: Type): KSerializer<Any>? =
serializerByJavaTypeImpl(type, failOnMissingTypeArgSerializer = false)
/**
* Retrieves a [KSerializer] for the given [java.lang.Class] instance of the Kotlin type or returns `null` if none is found.
* The given class must be annotated with [Serializable] or be one of the built-in types.
*
* The API avoids instantiation of the correspnding [KClass][Class.kotlin] on the best-effort basis.
*
* This is a [Class] counterpart of [KClass.serializerOrNull] with all the restrictions the original function implies,
* including the general recommendation to avoid uses of this API.
*/
@InternalSerializationApi
public fun <T : Any> Class<T>.serializerOrNull(): KSerializer<T>? =
constructSerializerForGivenTypeArgs() ?: kotlin.builtinSerializerOrNull()
@OptIn(ExperimentalSerializationApi::class)
private fun SerializersModule.serializerByJavaTypeImpl(type: Type, failOnMissingTypeArgSerializer: Boolean = true): KSerializer<Any>? =
when (type) {
is GenericArrayType -> {
genericArraySerializer(type, failOnMissingTypeArgSerializer)
}
is Class<*> -> typeSerializer(type, failOnMissingTypeArgSerializer)
is ParameterizedType -> {
val rootClass = (type.rawType as Class<*>)
val args = (type.actualTypeArguments)
val argsSerializers =
if (failOnMissingTypeArgSerializer) args.map { serializer(it) } else args.map { serializerOrNull(it) ?: return null }
when {
Set::class.java.isAssignableFrom(rootClass) -> SetSerializer(argsSerializers[0]) as KSerializer<Any>
List::class.java.isAssignableFrom(rootClass) || Collection::class.java.isAssignableFrom(rootClass) -> ListSerializer(
argsSerializers[0]
) as KSerializer<Any>
Map::class.java.isAssignableFrom(rootClass) -> MapSerializer(
argsSerializers[0],
argsSerializers[1]
) as KSerializer<Any>
Map.Entry::class.java.isAssignableFrom(rootClass) -> MapEntrySerializer(
argsSerializers[0],
argsSerializers[1]
) as KSerializer<Any>
Pair::class.java.isAssignableFrom(rootClass) -> PairSerializer(
argsSerializers[0],
argsSerializers[1]
) as KSerializer<Any>
Triple::class.java.isAssignableFrom(rootClass) -> TripleSerializer(
argsSerializers[0],
argsSerializers[1],
argsSerializers[2]
) as KSerializer<Any>
else -> {
// probably we should deprecate this method because it can't differ nullable vs non-nullable types
// since it uses Java TypeToken, not Kotlin one
val varargs = argsSerializers.map { it as KSerializer<Any?> }
(rootClass.kotlin.constructSerializerForGivenTypeArgs(*(varargs.toTypedArray())) as? KSerializer<Any>)
?: reflectiveOrContextual(rootClass.kotlin as KClass<Any>, varargs)
}
}
}
is WildcardType -> serializerByJavaTypeImpl(type.upperBounds.first())
else -> throw IllegalArgumentException("typeToken should be an instance of Class<?>, GenericArray, ParametrizedType or WildcardType, but actual type is $type ${type::class}")
}
@OptIn(ExperimentalSerializationApi::class)
private fun SerializersModule.typeSerializer(type: Class<*>, failOnMissingTypeArgSerializer: Boolean): KSerializer<Any>? {
return if (type.isArray && !type.componentType.isPrimitive) {
val eType: Class<*> = type.componentType
val s = if (failOnMissingTypeArgSerializer) serializer(eType) else (serializerOrNull(eType) ?: return null)
val arraySerializer = ArraySerializer(eType.kotlin as KClass<Any>, s)
arraySerializer as KSerializer<Any>
} else {
reflectiveOrContextual(type.kotlin as KClass<Any>, emptyList())
}
}
@OptIn(ExperimentalSerializationApi::class)
private fun SerializersModule.genericArraySerializer(
type: GenericArrayType,
failOnMissingTypeArgSerializer: Boolean
): KSerializer<Any>? {
val eType = type.genericComponentType.let {
when (it) {
is WildcardType -> it.upperBounds.first()
else -> it
}
}
val serializer = if (failOnMissingTypeArgSerializer) serializer(eType) else (serializerOrNull(eType) ?: return null)
val kclass = when (eType) {
is ParameterizedType -> (eType.rawType as Class<*>).kotlin
is KClass<*> -> eType
else -> throw IllegalStateException("unsupported type in GenericArray: ${eType::class}")
} as KClass<Any>
return ArraySerializer(kclass, serializer) as KSerializer<Any>
}
private fun Type.kclass(): KClass<*> = when (val it = this) {
is KClass<*> -> it
is Class<*> -> it.kotlin
is ParameterizedType -> it.rawType.kclass()
is WildcardType -> it.upperBounds.first().kclass()
is GenericArrayType -> it.genericComponentType.kclass()
else -> throw IllegalArgumentException("typeToken should be an instance of Class<?>, GenericArray, ParametrizedType or WildcardType, but actual type is $it ${it::class}")
}