ReferenceAdapterFactory

This commit is contained in:
DBotThePony 2023-01-22 19:19:10 +07:00
parent 580cfd53da
commit 2d7681628d
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -1,6 +1,9 @@
package ru.dbotthepony.kstarbound.io.json.util
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.TypeAdapterFactory
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
@ -55,6 +58,22 @@ class ReferenceAdapter<T>(val parent: TypeAdapter<T>) : TypeAdapter<T>() {
}
}
class ReferenceAdapterFactory(val parent: TypeAdapterFactory) : TypeAdapterFactory {
override fun <T : Any?> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
val candidate = parent.create(gson, type)
if (candidate != null) {
return ReferenceAdapter(candidate)
}
return null
}
}
fun <T> TypeAdapter<T>.asReference(): TypeAdapter<T> {
return ReferenceAdapter(this)
}
fun TypeAdapterFactory.asReference(): TypeAdapterFactory {
return ReferenceAdapterFactory(this)
}