Serialization of a lambda after its creation

前端 未结 1 1347
醉话见心
醉话见心 2020-12-11 02:00

I can serialize a lambda with the following syntax:

Runnable r = (Runnable & Serializable) () -> System.out.println(\"\");
try (ObjectOutput oo = new          


        
相关标签:
1条回答
  • 2020-12-11 02:21

    This is correct, and by design. Just as you cannot take a non-serializable object and make it serializable after instantiation, once a lambda is created, its serializability is set.

    A lambda is serializable if its target type is serializable (and its captured arguments are serializable.) Your first example is serializable because the target type is the intersection (Runnable & Serializable). Your two attempts to convert r fail because in both cases, r is a captured variable that is not serializable, and so the resulting lambda expression / method reference is not serializable. (The receiver for a bound method reference acts as a captured variable.)

    0 讨论(0)
提交回复
热议问题