A
A
Andrey Andryushchenko2015-05-08 17:00:16
Java
Andrey Andryushchenko, 2015-05-08 17:00:16

How to serialize and deserialize interfaces?

There is a class whose instance needs to be serialized and then deserialized accordingly, which has interface fields, which in the process of program operation can be different instances of anonymous classes that implement these interfaces. Now the question is how can these instances be serialized, so that during deserialization, all anonymous classes are restored. That is, the problem lies in the correct storage of actions in interfaces.
It is possible, in principle, for each interface to have a measurable name field containing information about an anonymous class, and then create an instance of such a class by name, but then there will be too many name options. And when deserializing, you have to consider many possible outcomes.
What should I do? How to do it right?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
1
1Michael1, 2015-05-08
@1Michael1

www.javatpoint.com/serialization-in-java

T
Timur, 2015-05-08
@timych

If the variables represent inheritors of one common type (interface), then in the case of json, you need to annotate it with the @JsonSubTypes annotation, in which you need to list all the inheritors. When you get a deserialized object, simply check whether it belongs to the required type (class) through instanceof and cast the object to this class. Here is a simple example (too lazy to write it myself :)): https://nickebbitt.wordpress.com/2014/01/31/handli...
PS: There is an error in the example - the abstract Animal class must implement Serializable

B
bromzh, 2015-05-09
@bromzh

If you use Jackson, then look here and here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question