blob: 458b99238a238ef1898c5998c3e5ddb7f5922da4 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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]
}
|