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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -