Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Created July 31, 2015 17:25
Show Gist options
  • Save thomasdarimont/072ea4d870190b14a6a4 to your computer and use it in GitHub Desktop.
Save thomasdarimont/072ea4d870190b14a6a4 to your computer and use it in GitHub Desktop.
Make Lambdas Serializable via Cast
package training.java8;
import java.io.*;
import java.util.Arrays;
import java.util.function.Consumer;
/**
* Created by tom on 22.07.15.
*/
public class SerializableLambdaExample {
public static void main(String[] args) throws Exception {
Runnable code = (Runnable & Serializable)() -> System.out.println("hello world");
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(code);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
Runnable serialized = (Runnable) ois.readObject();
serialized.run();
}
}
@beders
Copy link

beders commented Jul 31, 2015

Probably won't work across the wire to a different JVM since it's a dynamically generated class behind the scenes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment