2013-05-10 83 views
8

你如何反序列化不可變集合使用Kryo?除了我所做的事情之外,我還需要註冊一些東西嗎?如何使用Kryo反序列化不可變集合?

這裏是我的示例代碼

import com.esotericsoftware.kryo.Kryo 
import com.esotericsoftware.kryo.io.Input 
import com.esotericsoftware.kryo.io.Output 
import com.romix.scala.serialization.kryo._ 

val kryo = new Kryo 

// Serialization of Scala maps like Trees, etc 
kryo.addDefaultSerializer(classOf[scala.collection.Map[_,_]], classOf[ScalaMapSerializer]) 
kryo.addDefaultSerializer(classOf[scala.collection.generic.MapFactory[scala.collection.Map]], classOf[ScalaMapSerializer]) 

// Serialization of Scala sets 
kryo.addDefaultSerializer(classOf[scala.collection.Set[_]], classOf[ScalaSetSerializer]) 
kryo.addDefaultSerializer(classOf[scala.collection.generic.SetFactory[scala.collection.Set]], classOf[ScalaSetSerializer]) 

// Serialization of all Traversable Scala collections like Lists, Vectors, etc 
kryo.addDefaultSerializer(classOf[scala.collection.Traversable[_]], classOf[ScalaCollectionSerializer]) 

val filename = "c:\\aaa.bin" 
val ofile = new FileOutputStream(filename) 
val output2 = new BufferedOutputStream(ofile) 
val output = new Output(output2) 
kryo.writeClassAndObject(output, List("Test1", "Test2")) 
output.close() 

val ifile = new FileInputStream(filename) 
val input = new Input(new BufferedInputStream(ifile)) 
val deserialized = kryo.readClassAndObject(input) 
input.close() 

它拋出異常

Exception in thread "main" com.esotericsoftware.kryo.KryoException: Class cannot be created (missing no-arg constructor): scala.collection.immutable.$colon$colon 

回答

4

嘗試了這一點,因爲它爲我工作:FYI

import com.esotericsoftware.kryo.Kryo 
import com.esotericsoftware.kryo.io.Input 
import com.esotericsoftware.kryo.io.Output 
import com.romix.scala.serialization.kryo._ 
import org.objenesis.strategy.StdInstantiatorStrategy 

val kryo = new Kryo 

kryo.setRegistrationRequired(false) 
kryo.setInstantiatorStrategy(new StdInstantiatorStrategy()); 
kryo.register(classOf[scala.collection.immutable.$colon$colon[_]],60) 
kryo.register(classOf[scala.collection.immutable.Nil$],61) 
kryo.addDefaultSerializer(classOf[scala.Enumeration#Value], classOf[EnumerationSerializer]) 

val filename = "c:\\aaa.bin" 
val ofile = new FileOutputStream(filename) 
val output2 = new BufferedOutputStream(ofile) 
val output = new Output(output2) 
kryo.writeClassAndObject(output, List("Test1", "Test2")) 
output.close() 

val ifile = new FileInputStream(filename) 
val input = new Input(new BufferedInputStream(ifile)) 
val deserialized = kryo.readClassAndObject(input) 
input.close() 

作爲,我得到了這個工作通過查看romix庫的單元測試,然後做他們正在做的事情。

+0

看起來像'StdInstantiatorStrategy'是關鍵。我刪除了其餘的,它也工作。謝謝! – expert 2013-05-11 02:19:08

+1

你的例子不爲我編譯:(這些行上的問題:kryo.setInstantiatorStrategy(..)和kryo.addDefaultSerializer(..) – Adrian 2013-06-19 19:22:19