如何优雅地序列化 lambda?
例如,下面的代码抛出一个NotSerializableException. 如何在不创建SerializableRunnable“虚拟”界面的情况下修复它?
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(); } }
Java 8 引入了通过添加多个边界将对象强制转换为类型交集的可能性。在序列化的情况下,因此可以编写:
Runnable r = (Runnable & Serializable)() -> System.out.println("Serializable!");
并且 lambda 自动变得可序列化。