Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save functicons/38d9ada5cd04d9cbd4a99fbac58dc0f7 to your computer and use it in GitHub Desktop.
Save functicons/38d9ada5cd04d9cbd4a99fbac58dc0f7 to your computer and use it in GitHub Desktop.
Serialize and deserialize Java lambda functions and classes.
package com.example;
import java.io.*;
import java.util.function.Function;
/**
* Serialize and deserialize lambda functions and classes.
*/
public class Main {
public static void main(String[] args) throws Exception {
serializeAndDeserializeFunction();
serializeAndDeserializeClass();
}
private static void serializeAndDeserializeClass() throws Exception {
String path = "./serialized-class";
serialize(MyImpl.class, path);
System.out.println("Serialized class to " + path);
// Pretending we don't know the exact class of the serialized bits,
// create an instance from the class and use it through the interface.
Class<?> myImplClass = (Class<?>) deserialize(path);
System.out.println("Deserialized class from " + path);
MyInterface instance = (MyInterface) myImplClass.newInstance();
instance.hello("Java");
}
private static void serializeAndDeserializeFunction() throws Exception {
Function<Integer, String> fn = (Function<Integer, String> & Serializable) (n) -> "Hello " + n;
System.out.println("Run original function: " + fn.apply(10));
String path = "./serialized-fn";
serialize((Serializable) fn, path);
System.out.println("Serialized function to " + path);
Function<Integer, String> deserializedFn = (Function<Integer, String>) deserialize(path);
System.out.println("Deserialized function from " + path);
System.out.println("Run deserialized function: " + deserializedFn.apply(11));
}
private static void serialize(Serializable obj, String outputPath) throws IOException {
File outputFile = new File(outputPath);
if (!outputFile.exists()) {
outputFile.createNewFile();
}
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(outputFile))) {
outputStream.writeObject(obj);
}
}
private static Object deserialize(String inputPath) throws IOException, ClassNotFoundException {
File inputFile = new File(inputPath);
try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(inputFile))) {
return inputStream.readObject();
}
}
}
interface MyInterface {
void hello(String name);
}
class MyImpl implements MyInterface {
public void hello(String name) {
System.out.println("Hello " + name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment