0

I use spring with another frameworks nad I'm new in serialization.

What the problem:

I need to serialize MyClass object that contains the org.eclipse.jetty.websocket.api.Session session (which is non-serializable).

class MyClass {
  private org.eclipse.jetty.websocket.api.Session session; //NON-Serializable!

  private void writeObject(java.io.ObjectOutputStream out) throws IOException{
    out.writeObject(session);
  }

   private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
      session = (org.eclipse.jetty.websocket.api.Session) in.readObject();
   }
}

What the question:

I've read from here that it is possible to serialize object with non-serializable fields. But, org.eclipse.jetty.websocket.api.Session has not-trivial class hierarchy.

But when I try to doing so, it throw java.io.NotSerializableException: org.eclipse.jetty.websocket.common.WebSocketSession

Community
  • 1
  • 1
VB_
  • 45,112
  • 42
  • 145
  • 293
  • 1
    Have you tried transient keyword before variable? – Shamim Ahmmed Aug 27 '13 at 07:50
  • I dont know much about spring but yes you can serialize `MyClass` and skip the serialization of context using `transient` keyword. While de-serializing you can fetch the application context from where you fetch it initially. I hope that makes sense – Narendra Pathai Aug 27 '13 at 07:50
  • see addition section, and modified code. Why the exception? – VB_ Aug 27 '13 at 09:09
  • To serialize a session does not make sense either. You should rethink your design. – Henry Aug 27 '13 at 09:17

2 Answers2

2

I think it would not make sense if ClassPathXmlApplicationContext was Serializable because then you would have to Serialize all objects created in this context together with the context. Instead you could save the application.xml and then read it from file and recreate ClassPathXmlApplicationContext from it. To prevent serializing context field you can make it transient as shamimz suggested or simply null it before serializing MyClass instance

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1
class MyClass {
 private transient ClassPathXmlApplicationContext  context; //NON-Serializable!

}

Shamim Ahmmed
  • 8,265
  • 6
  • 25
  • 36
  • Sorry, but I also have Session, that MUST BE serialized. It can't be transient – VB_ Aug 27 '13 at 08:29
  • 1
    @Volodymyr yes, that's the point. If you mark MyClass as serializable, context as transient and session as _not_ transient, then you can save an instance of MyClass, it will save the session, and you just have to re-create the context after re-loading the serialised MyClass. – Ian Roberts Aug 27 '13 at 08:39
  • What you mean by save an instance of MyClass? Do you mean save session to file and than restore it? But what about multiple processes and synchronization? Please, get me a little example. – VB_ Aug 27 '13 at 08:47
  • Session is also non-serializable – VB_ Aug 27 '13 at 08:53