【发布时间】:2018-05-27 17:50:13
【问题描述】:
上下文:
所以我有一个要保存到文本文件中的方法调用。这样做的目的是将可运行的序列化对象保存到文本文件中,然后从文本文件中获取它以执行。
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
错误是:
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.
我理解错误,Runnable 是一个接口,它不能被序列化。但是,我还能做些什么来解决我的问题吗?
解决方案尝试 1. 错误
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
}
}
【问题讨论】:
-
必须保存为纯文本还是可以使用 Java 或 Protobuf 之类的二进制序列化?
-
您正在尝试序列化为 JSON?你期待什么输出?
-
我可以灵活地使用任何东西,但是我尝试了 ObjectOutputStream/writeObject 并且给出了相同的错误@AbhijitSarkar
-
@shmosel 您将其标记为重复,但该问题的接受答案并不能解决我的错误。请删除。
-
我认为,将这个问题标记为重复有点愚蠢。寻找 Gson 序列化的人会发现这个问题并且没有适当的 anwear。所以请删除重复的标志,因为它不能解决任何问题......