kotlin getSerializable
时间: 2023-10-08 14:09:47 浏览: 103
To make a class serializable in Kotlin, you need to implement the `Serializable` interface. Here's an example:
```kotlin
import java.io.Serializable
data class Person(val name: String, val age: Int): Serializable
fun main() {
val person = Person("John", 30)
// Serialization
val outputStream = FileOutputStream("person.ser")
val objectOutputStream = ObjectOutputStream(outputStream)
objectOutputStream.writeObject(person)
objectOutputStream.close()
outputStream.close()
// Deserialization
val inputStream = FileInputStream("person.ser")
val objectInputStream = ObjectInputStream(inputStream)
val deserializedPerson = objectInputStream.readObject() as Person
objectInputStream.close()
inputStream.close()
println(deserializedPerson)
}
```
In this example, the `Person` class implements the `Serializable` interface. We then serialize an instance of the `Person` class into a file called "person.ser". Afterward, we deserialize the object from the file and print it out. Note that the serialization and deserialization process requires handling exceptions, but they are omitted here for brevity.
阅读全文