如何在 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