Last active
November 3, 2016 05:26
-
-
Save ilya-g/f38d1855a872858101ac842cb6ca134d to your computer and use it in GitHub Desktop.
In order not to instantiate singletons with gson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.* | |
fun <T : Any> GsonBuilder.registerSingletonInstance(instance: T): GsonBuilder = | |
registerTypeAdapter(instance.javaClass, InstanceCreator { instance }) | |
fun main(args: Array<String>) { | |
// val gsonBuilder = GsonBuilder().registerTypeAdapterFactory(object : TypeAdapterFactory { | |
// override fun <T: Any> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? { | |
// val c: Class<T> = type.rawType as Class<T> | |
// return c.kotlin.objectInstance?.let { instance -> | |
// object : TypeAdapter<T>() { | |
// override fun read(`in`: JsonReader): T { | |
// `in`.beginObject() | |
// `in`.endObject() | |
// return instance | |
// } | |
// | |
// override fun write(out: JsonWriter, value: T) { | |
// out.beginObject() | |
// out.endObject() | |
// } | |
// } | |
// } | |
// } | |
// }) | |
val gson = GsonBuilder().registerSingletonInstance(Unit).create() | |
val u1 = Unit | |
val u2 = gson.fromJson("{}", Unit::class.java) | |
val u3 = Unit | |
println(u1 == u2) | |
println(u1 == u3) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment