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]
    }
  }

你可能感兴趣的:(java,scala,option,kryo,some)