有没有办法反序列化Runnable?

时间:2017-12-13 18:23:40

标签: java runnable restfb

上下文:

所以我有一个方法调用,我想保存到文本文件中。这样做的目的是将可运行的序列化对象保存到文本文件中,然后从文本文件中获取它以执行。

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
}
}

1 个答案:

答案 0 :(得分:-1)

我可以向你推荐一个盲目的尝试是创建一些runnable实现并尝试使用它。例如:

    public class Main {

    public static void main(String[] args) {

        Runnable a = new A();

        String gson = new Gson().toJson(a);
        Runnable runnable = new Gson().fromJson(gson, A.class);

        runnable.run();
    }

    public static class A implements Runnable{

        public void run() {
            System.out.println("Here im");
        }



    }
}

BTW将System.out.println("Here im");替换为yours client.publish

相关问题