Reputation: 3773
A lot of Callback
objects exist in my system. Callback
is defined as follows:
public interface Callback { void callback() throws Exception; } Callback cb = new Callback() { public void callback() { System.out.println("I'm here!"); } }
Now, I need to serialize these Callback
objects into bytes so that they can be stored in a redis server and be fetched back later to run the callback()
method.
Obviously the usual serialization libraries in Java such as Jackson won't work here. In order to run the callback()
code, the serialized bytes must contain the class information. The JDK serialization is an option here:
public interface Callback extends java.io.Serializable { void callback() throws Exception; } Callback cb = new Callback() { private static final long serialVersionUID = 1L; public void callback() { System.out.println("I'm here!"); } }
However, in this way, all the sub-classes of Callback
as well as the classes referenced from the callback()
method are required to implement the java.io.Serializable
interface, which is hard to control.
So, I wonder if there is another way of serialization which doesn't need all the kinds of restricts?
Upvotes: 0
Views: 642
Reputation: 533432
Java serialization doesn't store any more information than Jackson does. (Except Java serialization supports graphs and Jackson support trees) Neither store code with the serialized data.
Usually it's a bad idea to try to store code with the data. The code can either be;
You should instead make sure everything you might want to serialize is in the data, not the code.
the serialized bytes must contain the class information
This is not how serialization works. There is usually an assumption all the classes needed will be available to the process de-serializing the data.
all the sub-classes of Callback as well as the classes referenced from the callback()
When a parent is Serializable all of it's sub-classes will also be Serializable.
Upvotes: 5