Created
July 31, 2015 17:25
-
-
Save thomasdarimont/072ea4d870190b14a6a4 to your computer and use it in GitHub Desktop.
Make Lambdas Serializable via Cast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably won't work across the wire to a different JVM since it's a dynamically generated class behind the scenes.