如何优雅地序列化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自动变为可序列化的。