Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you override the stream writers in scala @serializable objects?

I now understand that scala @serializable objects can be used the same as a Java Serializable object. In a Java Serializable object there are methods you can override to change how the object streams: writeObject(ObjectOutputStream) / readObject(ObjectOutputStream).

Can you override or inject methods into a scala @serializable object allowing you to change how the object serializes?

like image 753
Fred Haslam Avatar asked Aug 09 '10 19:08

Fred Haslam


People also ask

Which interface allows to save an object and reconstruct it in separate JVM?

To be stored in an Object Stream, each object must implement either the Serializable or the Externalizable interface: For a Serializable class, Object Serialization can automatically save and restore fields of each class of an object and automatically handle classes that evolve by adding fields or supertypes.

Which of this class contains the method for Deserializing an object?

The ObjectInputStream class contains readObject() method for deserializing an object.

What happens if one of the member of class does not implement serializable interface in Java?

If our class does not implement Serializable interface, or if it is having a reference to a non- Serializable class, then the JVM will throw NotSerializableException . All transient and static fields do not get serialized.

How many methods do you implement if a class implements serializable interface?

Serializable interface has two methods, readResolve() and writeReplace() , which are used to read and write object in database.


2 Answers

As already stated, you can define your own writeObject and readObject methods.

@throws(classOf[java.io.IOException])
private def writeObject(out : java.io.ObjectOutputStream) : Unit = /* your definition  here */

However be careful when performing this on nested classes, objects or traits.

@serializable class Foo(x : Int) { @serializable object X { def y = x } }

If I serialize object X, it will actually serialize the containing Foo class, so this must also be serializable. This can be a PITA to deal with in custom serialization methods, so here's fair warning.

Another pain-point can be closure serialization. Try to keep a mental model of what variables are being captured in serialized closures. Ensure that these variables are something you'd want sent over IO!

like image 95
jsuereth Avatar answered Nov 09 '22 05:11

jsuereth


Yes, you can use the same methods in Scala as in Java:

@throws(classOf[IOException])
private def writeObject(out: ObjectOutputStream): Unit = // ...

@throws(classOf[IOException])
private def readObject(in: ObjectInputStream): Unit = // ...
like image 30
Aaron Novstrup Avatar answered Nov 09 '22 06:11

Aaron Novstrup