-1

I've a Class C which contains a Map property of another type (class A). I've implemented Serializable interface for class C and A

public class C {

    Map<A, Map<Interface_I, Double>> x;
private void writeObject(java.io.ObjectOutputStream stream) {...}
private void readObject(java.io.ObjectInputStream stream) {...}
}

For the interface I how can I make it serializable ?

Nasreddine
  • 184
  • 8

2 Answers2

1

Do you really need custom serialization with writeObject and readObject as described in the api?

To make implementations of an interface serializable just let it implement Serializable:

public Interface_I extends Serializable {...}

Is it that what you mean?

(Edit: refer serialization descriptions, too)

Community
  • 1
  • 1
Sergej Werfel
  • 1,335
  • 2
  • 14
  • 25
  • I want to take a snapshot of the object that takes long time to calculate some properties values and save it into a file in order to de-serialize it and restore its properties without need to re-compute its values. So, I've implemented serializable interface for my classes, it is not the right way to do that ? is there another way to achieve my goal ? – Nasreddine Aug 14 '15 at 07:02
  • When I understand your issue, it is enough to ensure that the class that should be serialized implements Serializable and all of its fields. Then you just save the object to a file: ObjectOutputStream o = new ObjectOutputStream( new FileOutputStream( filename ) ); o.writeObject(yourFile ); – Sergej Werfel Aug 14 '15 at 07:06
  • And don't forget to mark all non serializable fields with transient keyword – Sergej Werfel Aug 14 '15 at 07:09
  • But how an interface could be serializable since it do not have any state (properties) ? Or I should make serializable objects that implement Interface_I ? – Nasreddine Aug 14 '15 at 07:32
  • Making an interface serializable means that all classes that implements that interface must be serializable. Java can serialize all classes that implements serializable automatically. So actually yes, you need objects of classes that implements Interface_I, because you cannot instanciate Interface_I directly – Sergej Werfel Aug 14 '15 at 07:36
0

If the concrete class of the objects stored in the map implements Serializable, then the objects can be serialized.

You can force all these concrete classes to be serializable by making Interface_I extend Serializable, but that's usually a bad idea.

Also, I concur with Typischserg: you probably don't want to implement a custom serialization with writeObject() and readObject().

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255