From 3e64fdda48b8f2506756fc458f01f2e549d71720 Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Thu, 14 Jul 2016 11:02:36 +1000 Subject: SD-120 Non FunctionN lambdas should not be universally serializable Instead, we follow the example set by javac, and predicate serializability of bot anon-class and invokedynamic-based lambdas on whether or not the SAM type extends java.io.Serializable. Fixes https://github.com/scala/scala-dev/issues/120 --- test/files/run/lambda-serialization.scala | 2 +- test/files/run/sammy_seriazable.scala | 47 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 test/files/run/sammy_seriazable.scala (limited to 'test') diff --git a/test/files/run/lambda-serialization.scala b/test/files/run/lambda-serialization.scala index 0eee1193d7..08e235b1cb 100644 --- a/test/files/run/lambda-serialization.scala +++ b/test/files/run/lambda-serialization.scala @@ -1,6 +1,6 @@ import java.io.{ByteArrayInputStream, ObjectInputStream, ObjectOutputStream, ByteArrayOutputStream} -trait IntToString { def apply(i: Int): String } +trait IntToString extends java.io.Serializable { def apply(i: Int): String } object Test { def main(args: Array[String]): Unit = { diff --git a/test/files/run/sammy_seriazable.scala b/test/files/run/sammy_seriazable.scala new file mode 100644 index 0000000000..458b99238a --- /dev/null +++ b/test/files/run/sammy_seriazable.scala @@ -0,0 +1,47 @@ +import java.io._ + +trait NotSerializableInterface { def apply(a: Any): Any } +abstract class NotSerializableClass { def apply(a: Any): Any } +// SAM type that supports lambdas-as-invoke-dynamic +trait IsSerializableInterface extends java.io.Serializable { def apply(a: Any): Any } +// SAM type that still requires lambdas-as-anonhmous-classes +abstract class IsSerializableClass extends java.io.Serializable { def apply(a: Any): Any } + +object Test { + def main(args: Array[String]) { + val nsi: NotSerializableInterface = x => x + val nsc: NotSerializableClass = x => x + + import SerDes._ + assertNotSerializable(nsi) + assertNotSerializable(nsc) + assert(serializeDeserialize[IsSerializableInterface](x => x).apply("foo") == "foo") + assert(serializeDeserialize[IsSerializableClass](x => x).apply("foo") == "foo") + assert(ObjectStreamClass.lookup(((x => x): IsSerializableClass).getClass).getSerialVersionUID == 0) + } +} + +object SerDes { + def assertNotSerializable(a: AnyRef): Unit = { + try { + serialize(a) + assert(false) + } catch { + case _: NotSerializableException => // okay + } + } + + def serialize(obj: AnyRef): Array[Byte] = { + val buffer = new ByteArrayOutputStream + val out = new ObjectOutputStream(buffer) + out.writeObject(obj) + buffer.toByteArray + } + + def deserialize(a: Array[Byte]): AnyRef = { + val in = new ObjectInputStream(new ByteArrayInputStream(a)) + in.readObject + } + + def serializeDeserialize[T <: AnyRef](obj: T) = deserialize(serialize(obj)).asInstanceOf[T] +} -- cgit v1.2.3