Created
January 10, 2023 15:52
-
-
Save jodersky/50fa868214dfcb50d175b3f8b79fbac3 to your computer and use it in GitHub Desktop.
utilities for serializing and deserializing functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object LambdaUtil: | |
import java.lang.invoke.{MethodHandleInfo, SerializedLambda} | |
def serializeLambda(closure: AnyRef): Array[Byte] = | |
val writeReplace = closure.getClass.getDeclaredMethod("writeReplace") | |
writeReplace.setAccessible(true) | |
val serializable = writeReplace.invoke(closure).asInstanceOf[SerializedLambda] | |
val bytes = new java.io.ByteArrayOutputStream | |
val os = new java.io.ObjectOutputStream(bytes) | |
try | |
os.writeObject(serializable) | |
finally | |
os.close() | |
bytes.toByteArray | |
def deserializeLambda[A](loader: ClassLoader, bytes: Array[Byte]): A = | |
val byteStream = new java.io.ByteArrayInputStream(bytes) | |
val os = new java.io.ObjectInputStream(byteStream): | |
override def resolveClass(desc: java.io.ObjectStreamClass): Class[_] = | |
Class.forName(desc.getName, false, loader) | |
val lambda = os.readObject() | |
lambda.asInstanceOf[A] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment