在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; //序列化lambda函数 System.out.println("运行原始函数: " + fn.apply("Raja")); String path = "./serialized-fn"; serialize((Serializable) fn, path); System.out.println("序列化函数为" + path); Function<Strng, String> deserializedFn = (Function<String, String>) deserialize(path); System.out.println("反序列化函数 " + path); System.out.println("运行反序列化函数: " + 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(); } } }
输出结果
运行原始函数: Hello Raja 序列化函数为 ./serialized-fn 反序列化函数 ./serialized-fn 运行反序列化函数: Hello Raja