Context:
So I have a method call that I want to save into a text file. The purpose of this is saving a runnable serialized object into a text file and getting it later from the text file to execute.
final Runnable runnable = () -> { //Runnable object to serialize
client.publish("me/feed", GraphResponse.class,
Parameter.with("message", statusMessage));
};
final String gson = new Gson().toJson(runnable); // Serialized runnable as json. This works successfully.
final Runnable x = new Gson().fromJson(gson, Runnable.class); // error
Error is:
java.lang.RuntimeException: Unable to invoke no-args constructor for interface java.lang.Runnable. Registering an InstanceCreator with Gson for this type may fix this problem.
I understand the error, Runnable is an interface and it cannot be serialized. However is there something else that I can do that can solve my problem?
Solution Attempt 1. ERROR
public class RunnableImplementation implements Runnable, Serializable {
Runnable runnable;
public RunnableImplementation() {
}
public RunnableImplementation(final Runnable runnable) {
this.runnable = runnable;
}
@Override
public void run() {
runnable.run();
}
}
public class ExampleClass {
public static void main(String[] args) {
final Runnable runnable = () -> {
client.publish("me/feed", GraphResponse.class,
Parameter.with("message", statusMessage));
};
RunnableImplementation x = new RunnableImplementation(runnable);
String gson = new Gson().toJson(x);
RunnableImplementation runnableImplementation = new Gson().fromJson(gson, RunnableImplementation.class); // causes same error as above
}
}