单身系列在Kotlin

我想知道是否有可能在Kotlin反序列化(恢复属性值)的声明对象, 而不必手动分配属性或采取反思 。 以下片段进一步解释:

object Foo: Serializable { var propOne: String = "" // ... fun persist() { serialize(this) // no problem with serialization } fun restore(bytes: ByteArray) { val fooObj: Foo = deserialize(bytes) as Foo // It seems Kotlin allows us to use singleton as type! // obvioulsly either of the following is wrong: // this = fooObj // Foo = fooObj // ... is there a way to 'recover' the singleton (object) other than // manual assignment of properties (or reflection) ??? } } 

没有办法用新实例重新分配全局引用到单例。 最多可以在序列化过程中写出属性,然后在反序列化中直接读取属性并改变原始对象中的状态。 它将需要自定义代码,以通过直接分配或反射将属性分配到对象中。 如果你使自己的单例机制拥有一个实例,那么你可以换出另一个反序列化的实例。