Kotlin 中的单例序列化

Bas*_*ani 5 singleton serialization 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) ???    
    }
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*ard 2

无法使用新实例将全局引用重新分配给单例。最多可以在序列化期间写出属性,然后在反序列化时直接读取属性并改变原始对象中的状态。它将需要自定义代码,以便您通过直接分配或反射将属性分配给对象。如果您创建自己的单例机制来保存一个实例,您可以将其交换为反序列化的另一个实例,那就更好了。