Tag Archives: lambda

Lambdas and serialization

With the introduction of intersection cast in Java 8, it is now possible to write: Object o = (SomeType & SomeOtherType) otherObject;

One very interesting use case is Serialization as this allows us to automagically serialize a lambda effortlessly:

    File file = Files.createTempFile("lambda", "ser").toFile();
    try (ObjectOutput oo = new ObjectOutputStream(new FileOutputStream(file))) {
        Runnable r = (Runnable & Serializable) () -> System.out.println("I can be serialized!");
        oo.writeObject(r);
    }

    try (ObjectInput oi = new ObjectInputStream(new FileInputStream(file))) {
        Runnable  r = (Runnable) oi.readObject();
        r.run();
    }
Tagged , , ,