2011-01-23 81 views
11

我在Scala上遇到問題。我用@transient lazy val字段序列化一個類的實例。然後我將其反序列化,該字段分配爲null。我期待反序列化後的懶惰評價。我該怎麼辦?@transient lazy val字段序列化

以下是一個示例代碼。

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(); 
    } 
    } 

} 

回答

9

有一個在Scala的Trac的一對夫婦在此門票:

我勸你要測試的2.9幹線的身材,它可能已經被修復了。

+0

非常感謝。我會嘗試2.9。 – hydrocul 2011-01-23 11:52:22