How to serialize a lambda?

后端 未结 5 870
眼角桃花
眼角桃花 2020-11-22 08:29

How can I elegantly serialize a lambda?

For example, the code below throws a NotSerializableException. How can I fix it without creating a Seriali

5条回答
  •  自闭症患者
    2020-11-22 09:21

    Java 8 introduces the possibility to cast an object to an intersection of types by adding multiple bounds. In the case of serialization, it is therefore possible to write:

    Runnable r = (Runnable & Serializable)() -> System.out.println("Serializable!");
    

    And the lambda automagically becomes serializable.

提交回复
热议问题