【问题标题】:Is there a way to deserialize a Runnable? [duplicate]有没有办法反序列化 Runnable? [复制]
【发布时间】: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。所以请删除重复的标志,因为它不能解决任何问题......

标签: java runnable restfb


【解决方案1】:

我可以向您推荐的一个盲目尝试是创建一些可运行的实现并使用它来尝试您的代码。例如:

    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");
        }



    }
}

顺便说一句,将我的 System.out.println("Here im"); 替换为 yours client.publish

【讨论】:

  • 是的,我现在正在尝试。想知道是否有其他解决方案。最好更“优雅”
  • 试过但失败了。
  • 谁给我减一,非常感谢。吉尔你做了 Runnable 的实现有点乱。我编辑我的帖子以获得确切的教程如何做到这一点......你制作的代码再次包含 Runnable 的属性......
  • 最后一个信息,你的客户会遇到麻烦。客户端属性必须以相同的方式“可序列化”。如果做不到,你真的需要另辟蹊径,因为 Gson 没有为这个用例做好准备(它是为 pojo 类设计的)。
  • 感谢您的回复。我很可能会尝试另一种方法,因为我认为序列化 Runnable 在这种情况下不会起作用。
猜你喜欢
  • 2019-12-26
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
  • 1970-01-01
  • 2020-01-11
相关资源
最近更新 更多