Created
January 28, 2021 00:05
-
-
Save themoritz/87af7c71b3467d8186eed67528a2c55b to your computer and use it in GitHub Desktop.
Custom Serialization in Kotlin
This file contains hidden or 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 java.io.ByteArrayOutputStream | |
| import java.io.ObjectInputStream | |
| import java.io.ObjectOutputStream | |
| import java.io.Serializable | |
| data class Moritz(val x: Int) | |
| data class Foo( | |
| @Transient | |
| var bar: Moritz, | |
| val baz: Int | |
| ) : Serializable { | |
| private fun writeObject(oss: ObjectOutputStream) { | |
| oss.defaultWriteObject() | |
| oss.writeObject(10) | |
| } | |
| private fun readObject(ois: ObjectInputStream) { | |
| ois.defaultReadObject() | |
| bar = Moritz(ois.readObject() as Int) | |
| } | |
| } | |
| val foo = Foo(Moritz(1), 1) | |
| val os = ByteArrayOutputStream() | |
| val oos = ObjectOutputStream(os).writeObject(foo) | |
| val bs = os.toByteArray() | |
| val recovered = ObjectInputStream(bs.inputStream()).readObject() as Foo | |
| println(recovered) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment