@transient惰性val字段序列化 [英] @transient lazy val field serialization
本文介绍了@transient惰性val字段序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Scala上遇到问题.我用@transient lazy val
字段序列化了一个类的实例.然后我将其反序列化,该字段被分配为null
.我期望反序列化后的懒惰评估.我该怎么办?
I have a problem on Scala. I serialize an instance of class with @transient lazy val
field. And then I deserialize it, the field is assigned null
. I expect the lazy evaluation after deserialization. What should I do?
以下是示例代码.
object Test {
def main(args: Array[String]){
//----------------
// ClassA - with @transient
//----------------
val objA1 = ClassA("world");
println(objA1);
// This works as expected as follows:
// "Good morning."
// "Hello, world"
saveObject("testA.dat", objA1);
val objA2 = loadObject("testA.dat").asInstanceOf[ClassA];
println(objA2);
// I expect this will work as follows:
// "Good morning."
// "Hello, world"
// but actually it works as follows:
// "null"
//----------------
// ClassB - without @transient
// this works as expected
//----------------
val objB1 = ClassB("world");
println(objB1);
// This works as expected as follows:
// "Good morning."
// "Hello, world"
saveObject("testB.dat", objB1);
val objB2 = loadObject("testB.dat").asInstanceOf[ClassB];
println(objB2);
// This works as expected as follows:
// "Hello, world"
}
case class ClassA(name: String){
@transient private lazy val msg = {
println("Good morning.");
"Hello, " + name;
}
override def toString = msg;
}
case class ClassB(name: String){
private lazy val msg = {
println("Good morning.");
"Hello, " + name;
}
override def toString = msg;
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
def saveObject(fname: String, obj: AnyRef){
val fop = new FileOutputStream(fname);
val oop = new ObjectOutputStream(fop);
try {
oop.writeObject(obj);
} finally {
oop.close();
}
}
def loadObject(fname: String): AnyRef = {
val fip = new FileInputStream(fname);
val oip = new ObjectInputStream(fip);
try {
oip.readObject();
} finally {
oip.close();
}
}
}
推荐答案
Scala的Trac中有几张票:
There's a couple of tickets on this in Scala's Trac:
- 1573
- 1574
我建议您针对2.9的主干版本进行测试,因为它可能已经修复.
I'd advise you to test against a trunk build of 2.9, as it may already be fixed.
这篇关于@transient惰性val字段序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文