简体   繁体   中英

Can Delegates.observable() be serializable?

Given a class

class Pizza(name: String?) : Serializable {
    var name: String? by Delegates.observable(name, {_,_,_ -> })
}

Why is this not serializable? It crashes with

Caused by: java.io.NotSerializableException: com.xxx.xxx.Pizza$$special$$inlined$observable$1

The reason behind your issue is the delegates are stored as an array in a synthetic backing field which is neither marked as transient nor serialziable, so it prevents the serialization. However just marking the property with @Transient will probably ruin your serialized form. And may not work at all

Before JetBrains decide to make a final resolution to this issue, you should use writeReplace and readResolve to override the default serializing mechanism. I've provided a sample solution below:

class Pizza(name: String?) : Serializable {
    @Transient var name: String? by Delegates.observable(name)
    private fun writeReplace(stream: ObjectOutputStream): Object = SerialProxy(name)
    private class SerialProxy(var name: String): Serializable {
        private fun readResolve(): Object = Pizza(name)
    }
}

readObject()/writeObject() doesn't work because you have no way to set the delegate after constructor is invoked without using reflection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM