如何序列化 lambda?
2022-08-31 06:55:37
如何优雅地序列化 lambda?
例如,下面的代码会抛出一个 .如何在不创建“虚拟”界面的情况下修复它?NotSerializableException
SerializableRunnable
public static void main(String[] args) throws Exception {
File file = Files.createTempFile("lambda", "ser").toFile();
try (ObjectOutput oo = new ObjectOutputStream(new FileOutputStream(file))) {
Runnable r = () -> System.out.println("Can I be serialized?");
oo.writeObject(r);
}
try (ObjectInput oi = new ObjectInputStream(new FileInputStream(file))) {
Runnable r = (Runnable) oi.readObject();
r.run();
}
}