Skip to content

Instantly share code, notes, and snippets.

@jodersky
Created January 10, 2023 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jodersky/50fa868214dfcb50d175b3f8b79fbac3 to your computer and use it in GitHub Desktop.
Save jodersky/50fa868214dfcb50d175b3f8b79fbac3 to your computer and use it in GitHub Desktop.
utilities for serializing and deserializing functions
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