如何在 Java 中序列化 lambda 函数?
序列化是一个将对象状态写入字节流的过程,以便我们可以在网络中传输它。如果其目标类型和捕获的参数已序列化,则我们可以序列化lambda表达式。但是,类似于内部类,强烈不建议序列化 lambda 表达式。
在以下示例中,我们可以使用Function接口序列化和反序列化一个 lambda 函数。
示例
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();
}
}
}输出
Run original function: Hello Raja Serialized function to ./serialized-fn Deserialized function from ./serialized-fn Run deserialized function: Hello Raja
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP