serialize scala.Some with Kryo
对scala反射不太明了,kryo里涉及到scala内置类时,经常因为没有无参构造而抛异常
Caused by: java.lang.InstantiationException: scala.Some at java.lang.Class.newInstance0(Class.java:357) at java.lang.Class.newInstance(Class.java:325) at com.esotericsoftware.kryo.Kryo.newInstance(Kryo.java:676) ... 12 more
思路是,转化成java基础类解决;
obj.asInstanceOf[Option[Any]]这句简直要了亲命了,一开始在想尽办法想把这个generic的T找到,最后发现Any解决所有问题,对于scala的generic还是需要研究
def writeObjectData(buffer: ByteBuffer, obj: Object): Unit = { if (obj == None) { kryo.writeClassAndObject(buffer, None) } else { kryo.writeClassAndObject(buffer, obj.asInstanceOf[Option[Any]].get) } } def readObjectData[T](buffer: ByteBuffer, objType: java.lang.Class[T]): T = { val obj = kryo.readClassAndObject(buffer) if (obj == None) { None.asInstanceOf[T] } else { Some(obj).asInstanceOf[T] } }
相关推荐
匆匆那些年 2020-10-15
TheBigBlue 2020-07-28
shenwenjie 2020-07-07
muhongdi 2020-07-07
waitwolf 2020-07-08
yunfenglee 2020-07-08
yunfenglee 2020-07-08
kekeromer 2020-07-08
匆匆那些年 2020-07-07
liqinglin0 2020-07-05
TheBigBlue 2020-07-05
kekeromer 2020-06-13
zhixingheyitian 2020-06-08
TheBigBlue 2020-06-06
liqinglin0 2020-06-01
liqinglin0 2020-06-01
yunfenglee 2020-05-30
MICKEYSTUDY 2020-05-28
muhongdi 2020-05-19