最佳答案
我怎样才能优雅地连载一个 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();
}
}