java - How to serialize a lambda? -
how can elegantly serialize lambda?
for example, code below throws notserializableexception
. how can fix without creating serializablerunnable
"dummy" interface?
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 serialized?"); oo.writeobject(r); } try (objectinput oi = new objectinputstream(new fileinputstream(file))) { runnable r = (runnable) oi.readobject(); r.run(); } }
java 8 introduces possibility cast object intersection of types adding multiple bounds. in case of serialization, therefore possible write:
runnable r = (runnable & serializable)() -> system.out.println("serializable!");
and lambda automagically becomes serializable.
Comments
Post a Comment