How to serialize a lambda?

后端 未结 5 821
眼角桃花
眼角桃花 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:04

    Very ugly cast. I prefer to define a Serializable extension to the functional interface I'm using

    For example:

    interface SerializableFunction extends Function, Serializable {}
    interface SerializableConsumer extends Consumer, Serializable {}
    

    then the method accepting the lambda can be defined as such :

    private void someFunction(SerializableFunction function) {
       ...
    }
    

    and calling the function you can pass your lambda without any ugly cast:

    someFunction(arg -> doXYZ(arg));
    

提交回复
热议问题