title: Basic Serialization sidebar_position: 2 id: java_basic_serialization license: | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
This page covers basic serialization patterns and Fory instance creation.
For single-threaded applications:
Fory fory = Fory.builder() .withLanguage(Language.JAVA) // enable reference tracking for shared/circular reference. // Disable it will have better performance if no duplicate reference. .withRefTracking(false) .withCompatibleMode(CompatibleMode.SCHEMA_CONSISTENT) // enable type forward/backward compatibility // disable it for small size and better performance. // .withCompatibleMode(CompatibleMode.COMPATIBLE) // enable async multi-threaded compilation. .withAsyncCompilation(true) .build(); byte[] bytes = fory.serialize(object); System.out.println(fory.deserialize(bytes));
For multi-threaded applications:
ThreadSafeFory fory = Fory.builder() .withLanguage(Language.JAVA) // enable reference tracking for shared/circular reference. // Disable it will have better performance if no duplicate reference. .withRefTracking(false) // compress int for smaller size // .withIntCompressed(true) // compress long for smaller size // .withLongCompressed(true) .withCompatibleMode(CompatibleMode.SCHEMA_CONSISTENT) // enable type forward/backward compatibility // disable it for small size and better performance. // .withCompatibleMode(CompatibleMode.COMPATIBLE) // enable async multi-threaded compilation. .withAsyncCompilation(true) .buildThreadSafeFory(); byte[] bytes = fory.serialize(object); System.out.println(fory.deserialize(bytes));
Fory provides efficient deep copy functionality:
Fory fory = Fory.builder().withRefCopy(true).build(); SomeClass a = xxx; SomeClass copied = fory.copy(a);
When disabled, deep copy will ignore circular and shared references. Same reference of an object graph will be copied into different objects in one Fory#copy:
Fory fory = Fory.builder().withRefCopy(false).build(); SomeClass a = xxx; SomeClass copied = fory.copy(a);
// Serialize object to byte array byte[] bytes = fory.serialize(object); // Deserialize byte array to object Object obj = fory.deserialize(bytes);
// Serialize with explicit type byte[] bytes = fory.serializeJavaObject(object); // Deserialize with expected type MyClass obj = fory.deserializeJavaObject(bytes, MyClass.class);
// Serialize with type information byte[] bytes = fory.serializeJavaObjectAndClass(object); // Deserialize with embedded type info Object obj = fory.deserializeJavaObjectAndClass(bytes);