Scala Serialization

Serialization: The process of writing state of an object into a file, Basically it is a process of converting an object from Java supported form into file supported form or network supported form.

Object means binary data to write into the file we need a stream.

By using FileOutputStream and ObjectOutputStream classes we can achieve serilization.

Deserialization: The process of reading the state of the object from the file is called Deserialization, Basically, it is a process of converting an object from file supported form or network supported into form Java supported form.



By using FileInputStream and ObjectInputStream classes we can achieve deserilization.



import java.io._

@SerialVersionUID(123L)
class Dog(var i:Int= 10,var j:Int= 20) extends  Serializable{

}


object Dog{
  def main(args:Array[String]){
    var d1 = new Dog()
 
    val oos = new ObjectOutputStream(new FileOutputStream("dog.ser"))
    oos.writeObject(d1)
    oos.close
 
 
    val ois = new ObjectInputStream(new FileInputStream("dog.ser"))
    val d2 = ois.readObject.asInstanceOf[Dog]
    ois.close
    println(d2.i)
    println(d2.j)
 
  }
}



We can serialize the only serializable object. To make an object serializable we need to implement serializable interface.It is a marker interface and available in the java.io package.
You will get a runtime exception Not serializable exception if you haven't implemented serializable interface.

Transient : if we use a Transient variable in the class that variable is not a part of the serialization. JVM ignore the original value and assign a default variable to that variable.

So we can say transient means not to participate in serialization.


No comments:

Post a Comment