How to serialize a lambda?

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

    The same construction can be used for method references. For example this code:

    import java.io.Serializable;
    
    public class Test {
        static Object bar(String s) {
            return "make serializable";
        }
    
        void m () {
            SAM s1 = (SAM & Serializable) Test::bar;
            SAM s2 = (SAM & Serializable) t -> "make serializable";
        }
    
        interface SAM {
            Object action(String s);
        }
    }
    

    defines a lambda expression and a method reference with a serializable target type.

提交回复
热议问题