Kryo的语法与
java序列化相似.创建kryo对象以及输出/输入,并使用kryos方法之一来执行序列化/反序列化
> kryo.writeClassAndObject(output,object); //如果具体类未知(可以为null)
> kryo.writeObjectOrNull(output,someObject); //如果对象可以为null
> kryo.writeObject(output,someObject); //不能为null,具体类是已知的
每个写入与读取配对
> SomeClass object =(SomeClass)kryo.readClassAndObject(input);
> SomeClass someObject = kryo.readObjectOrNull(input,SomeClass.class);
> SomeClass someObject = kryo.readObject(input,SomeClass.class);
以下是使用writeClassAndObject的示例,该函数将Vector3d序列化为文件并再次返回.
public class KryoTest {
public static void main(String[] args){
Vector3d someObject=new Vector3d(1,2,3);
//serialise object
//try-with-resources used to autoclose resources
try (Output output = new Output(new FileOutputStream("KryoTest.ser"))) {
Kryo kryo=new Kryo();
kryo.writeClassAndObject(output, someObject);
} catch (FileNotFoundException ex) {
Logger.getLogger(KryTest.class.getName()).log(Level.SEVERE, null, ex);
}
//deserialise object
Vector3d retrievedObject=null;
try (Input input = new Input( new FileInputStream("KryoTest.ser"))){
Kryo kryo=new Kryo();
retrievedObject=(Vector3d)kryo.readClassAndObject(input);
} catch (FileNotFoundException ex) {
Logger.getLogger(KryTest.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Retrieved from file: " + retrievedObject.toString());
}
}