
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Serialize a Lambda Function in Java
The Serialization is a process for writing the state of an object into a byte stream so that we can transfer it over the network. We can serialize a lambda expression if its target type and its captured arguments have serialized. However, like inner classes, the serialization of lambda expressions is strongly discouraged.
In the below example, we can serialize and deserialize a lambda function using a Function interface.
Example
import java.io.*; import java.util.function.Function; interface MyInterface { void hello(String name); } class MyImpl implements MyInterface { public void hello(String name) { System.out.println("Hello " + name); } } public class SerializeDeSerializeLambdaTest { public static void main(String[] args) throws Exception { serializeAndDeserializeFunction(); } private static void serializeAndDeserializeFunction() throws Exception { Function<String, String> fn = (Function<String, String> & Serializable) (n) -> "Hello " + n; // serialize a lambda function System.out.println("Run original function: " + fn.apply("Raja")); String path = "./serialized-fn"; serialize((Serializable) fn, path); System.out.println("Serialized function to " + path); Function<Strng, String> deserializedFn = (Function<String, String>) deserialize(path); System.out.println("Deserialized function from " + path); System.out.println("Run deserialized function: " + deserializedFn.apply("Raja")); } 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(); } } }
Output
Run original function: Hello Raja Serialized function to ./serialized-fn Deserialized function from ./serialized-fn Run deserialized function: Hello Raja
Advertisements