Class Kryo
- java.lang.Object
-
- com.esotericsoftware.kryo.Kryo
-
public class Kryo extends Object
Maps classes to serializers so object graphs can be serialized automatically.- Author:
- Nathan Sweet
-
-
Constructor Summary
Constructors Constructor Description Kryo()
Creates a new Kryo with aDefaultClassResolver
and references disabled.Kryo(ClassResolver classResolver, ReferenceResolver referenceResolver)
Kryo(ReferenceResolver referenceResolver)
Creates a new Kryo with aDefaultClassResolver
.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description void
addDefaultSerializer(Class type, Serializer serializer)
Instances of the specified class will use the specified serializer whenregister(Class)
orregister(Class, int)
are called.void
addDefaultSerializer(Class type, SerializerFactory serializerFactory)
Instances of the specified class will use the specified factory to create a serializer whenregister(Class)
orregister(Class, int)
are called.void
addDefaultSerializer(Class type, Class<? extends Serializer> serializerClass)
Instances of the specified class will use the specified serializer whenregister(Class)
orregister(Class, int)
are called.<T> T
copy(T object)
Returns a deep copy of the object.<T> T
copy(T object, Serializer serializer)
Returns a deep copy of the object using the specified serializer.<T> T
copyShallow(T object)
Returns a shallow copy of the object.<T> T
copyShallow(T object, Serializer serializer)
Returns a shallow copy of the object using the specified serializer.ClassLoader
getClassLoader()
ClassResolver
getClassResolver()
ObjectMap
getContext()
Name/value pairs that are available to all serializers.Serializer
getDefaultSerializer(Class type)
Returns the best matching serializer for a class.protected Serializer
getDefaultSerializerForAnnotatedType(Class type)
int
getDepth()
Returns the number of child objects away from the object graph root.Generics
getGenerics()
Tracks the generic type arguments and actual classes for type variables in the object graph during seralization.ObjectMap
getGraphContext()
Name/value pairs that are available to all serializers and are cleared after each object graph is serialized or deserialized.org.objenesis.strategy.InstantiatorStrategy
getInstantiatorStrategy()
int
getNextRegistrationId()
Returns the lowest, next available integer ID.IdentityMap
getOriginalToCopyMap()
Returns the internal map of original to copy objects when a copy method is used.ReferenceResolver
getReferenceResolver()
boolean
getReferences()
Registration
getRegistration(int classID)
Registration
getRegistration(Class type)
If the class is not registered andsetRegistrationRequired(boolean)
is false, it is automatically registered using thedefault serializer
.Serializer
getSerializer(Class type)
Returns the serializer for the registration for the specified class.boolean
getWarnUnregisteredClasses()
boolean
isClosure(Class type)
Returns true if the specified type is a closure.boolean
isFinal(Class type)
Returns true if the specified type is final.boolean
isRegistrationRequired()
protected Serializer
newDefaultSerializer(Class type)
Called bygetDefaultSerializer(Class)
when no default serializers matched the type.<T> T
newInstance(Class<T> type)
Creates a new instance of a class usingRegistration.getInstantiator()
.protected org.objenesis.instantiator.ObjectInstantiator
newInstantiator(Class type)
Returns a new instantiator for creating new instances of the specified type.Registration
readClass(Input input)
Reads a class and returns its registration.Object
readClassAndObject(Input input)
Reads the class and object or null using the registered serializer.<T> T
readObject(Input input, Class<T> type)
Reads an object using the registered serializer.<T> T
readObject(Input input, Class<T> type, Serializer serializer)
Reads an object using the specified serializer.<T> T
readObjectOrNull(Input input, Class<T> type)
Reads an object or null using the registered serializer.<T> T
readObjectOrNull(Input input, Class<T> type, Serializer serializer)
Reads an object or null using the specified serializer.void
reference(Object object)
Called bySerializer.read(Kryo, Input, Class)
andSerializer.copy(Kryo, Object)
before Kryo can be used to deserialize or copy child objects.Registration
register(Registration registration)
Stores the specified registration.Registration
register(Class type)
Registers the class using the lowest, next available integer ID and thedefault serializer
.Registration
register(Class type, int id)
Registers the class using the specified ID and thedefault serializer
.Registration
register(Class type, Serializer serializer)
Registers the class using the lowest, next available integer ID and the specified serializer.Registration
register(Class type, Serializer serializer, int id)
Registers the class using the specified ID and serializer.void
reset()
Resets object graph state: unregistered class names, references to previously serialized or deserialized objects, theoriginal to copy map
, and thegraph context
.void
setAutoReset(boolean autoReset)
If true (the default),reset()
is called automatically after an entire object graph has been read or written.void
setClassLoader(ClassLoader classLoader)
Sets the classloader to resolve unregistered class names to classes.void
setCopyReferences(boolean copyReferences)
If true, whencopy(Object)
and other copy methods encounter an object for the first time the object is copied and on subsequent encounters the copied object is used.void
setDefaultSerializer(SerializerFactory serializer)
Sets the serializer factory to use when nodefault serializers
match an object's type.void
setDefaultSerializer(Class<? extends Serializer> serializer)
Sets the serializer to use when nodefault serializers
match an object's type.void
setInstantiatorStrategy(org.objenesis.strategy.InstantiatorStrategy strategy)
Sets the strategy used bynewInstantiator(Class)
for creating objects.void
setMaxDepth(int maxDepth)
Sets the maxiumum depth of an object graph.void
setOptimizedGenerics(boolean optimizedGenerics)
If true (the default), Kryo attempts to use generic type information to optimize the serialized size.void
setReferenceResolver(ReferenceResolver referenceResolver)
Sets the reference resolver and enables references.boolean
setReferences(boolean references)
If true, each appearance of an object in the graph after the first is stored as an integer ordinal.void
setRegistrationRequired(boolean registrationRequired)
If true, an exception is thrown when an unregistered class is encountered.void
setWarnUnregisteredClasses(boolean warnUnregisteredClasses)
If true, kryo writes a warn log entry when an unregistered class is encountered.protected String
unregisteredClassMessage(Class type)
Registration
writeClass(Output output, Class type)
Writes a class and returns its registration.void
writeClassAndObject(Output output, Object object)
Writes the class and object or null using the registered serializer.void
writeObject(Output output, Object object)
Writes an object using the registered serializer.void
writeObject(Output output, Object object, Serializer serializer)
Writes an object using the specified serializer.void
writeObjectOrNull(Output output, Object object, Serializer serializer)
Writes an object or null using the specified serializer.void
writeObjectOrNull(Output output, Object object, Class type)
Writes an object or null using the registered serializer for the specified type.
-
-
-
Field Detail
-
NULL
public static final byte NULL
- See Also:
- Constant Field Values
-
NOT_NULL
public static final byte NOT_NULL
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
Kryo
public Kryo()
Creates a new Kryo with aDefaultClassResolver
and references disabled.
-
Kryo
public Kryo(ReferenceResolver referenceResolver)
Creates a new Kryo with aDefaultClassResolver
.- Parameters:
referenceResolver
- May be null to disable references.
-
Kryo
public Kryo(ClassResolver classResolver, ReferenceResolver referenceResolver)
- Parameters:
referenceResolver
- May be null to disable references.
-
-
Method Detail
-
setDefaultSerializer
public void setDefaultSerializer(SerializerFactory serializer)
Sets the serializer factory to use when nodefault serializers
match an object's type. Default isSerializerFactory.FieldSerializerFactory
.- See Also:
newDefaultSerializer(Class)
-
setDefaultSerializer
public void setDefaultSerializer(Class<? extends Serializer> serializer)
Sets the serializer to use when nodefault serializers
match an object's type. Default isFieldSerializer
.- See Also:
newDefaultSerializer(Class)
-
addDefaultSerializer
public void addDefaultSerializer(Class type, Serializer serializer)
Instances of the specified class will use the specified serializer whenregister(Class)
orregister(Class, int)
are called.- See Also:
setDefaultSerializer(Class)
-
addDefaultSerializer
public void addDefaultSerializer(Class type, SerializerFactory serializerFactory)
Instances of the specified class will use the specified factory to create a serializer whenregister(Class)
orregister(Class, int)
are called.- See Also:
setDefaultSerializer(Class)
-
addDefaultSerializer
public void addDefaultSerializer(Class type, Class<? extends Serializer> serializerClass)
Instances of the specified class will use the specified serializer whenregister(Class)
orregister(Class, int)
are called. Serializer instances are created as needed viaSerializerFactory.ReflectionSerializerFactory.newSerializer(Kryo, Class, Class)
. By default, the following classes have a default serializer set:boolean Boolean byte Byte char Character short Short int Integer long Long float Float double Double String byte[] char[] short[] int[] long[] float[] double[] String[] Object[] Map BigInteger BigDecimal KryoSerializable Collection Date Collections.emptyList Collections.singleton Currency StringBuilder Enum Collections.emptyMap Collections.emptySet Calendar StringBuffer Class Collections.singletonList Collections.singletonMap TimeZone BitSet Locale Arrays.asList TreeMap URL EnumSet Charset ConcurrentSkipListMap TreeSet PriorityQueue Optional OptionalInt OptionalLong OptionalDouble Duration Instant LocalDate LocalTime LocalDateTime ZoneOffset ZoneId OffsetTime OffsetDateTime ZonedDateTime Year YearMonth MonthDay Period List.of Set.of Map.of
-
getDefaultSerializer
public Serializer getDefaultSerializer(Class type)
Returns the best matching serializer for a class. This method can be overridden to implement custom logic to choose a serializer.
-
getDefaultSerializerForAnnotatedType
protected Serializer getDefaultSerializerForAnnotatedType(Class type)
-
newDefaultSerializer
protected Serializer newDefaultSerializer(Class type)
Called bygetDefaultSerializer(Class)
when no default serializers matched the type. Subclasses can override this method to customize behavior. The default implementation callsSerializerFactory.newSerializer(Kryo, Class)
using thedefault serializer
.
-
register
public Registration register(Class type)
Registers the class using the lowest, next available integer ID and thedefault serializer
. If the class is already registered, no change will be made and the existing registration will be returned. Registering a primitive also affects the corresponding primitive wrapper.Because the ID assigned is affected by the IDs registered before it, the order classes are registered is important when using this method. The order must be the same at deserialization as it was for serialization.
-
register
public Registration register(Class type, int id)
Registers the class using the specified ID and thedefault serializer
. If the class is already registered this has no effect and the existing registration is returned. Registering a primitive also affects the corresponding primitive wrapper.IDs must be the same at deserialization as they were for serialization.
- Parameters:
id
- Must be >= 0. Smaller IDs are serialized more efficiently. IDs 0-8 are used by default for primitive types and String, but these IDs can be repurposed.
-
register
public Registration register(Class type, Serializer serializer)
Registers the class using the lowest, next available integer ID and the specified serializer. If the class is already registered, the existing entry is updated with the new serializer. Registering a primitive also affects the corresponding primitive wrapper.Because the ID assigned is affected by the IDs registered before it, the order classes are registered is important when using this method. The order must be the same at deserialization as it was for serialization.
-
register
public Registration register(Class type, Serializer serializer, int id)
Registers the class using the specified ID and serializer. Providing an ID that is already in use by the same type will cause the old entry to be overwritten. Registering a primitive also affects the corresponding primitive wrapper.IDs must be the same at deserialization as they were for serialization.
- Parameters:
id
- Must be >= 0. Smaller IDs are serialized more efficiently. IDs 0-9 are used by default for primitive types and their wrappers, String, and void, but these IDs can be repurposed.
-
register
public Registration register(Registration registration)
Stores the specified registration. If the ID is already in use by the same type, the old entry is overwritten. Registering a primitive also affects the corresponding primitive wrapper.IDs must be the same at deserialization as they were for serialization.
Registration can be suclassed to efficiently store per type information, accessible in serializers via
getRegistration(Class)
.
-
getNextRegistrationId
public int getNextRegistrationId()
Returns the lowest, next available integer ID.
-
getRegistration
public Registration getRegistration(Class type)
If the class is not registered andsetRegistrationRequired(boolean)
is false, it is automatically registered using thedefault serializer
.- Throws:
IllegalArgumentException
- if the class is not registered andsetRegistrationRequired(boolean)
is true.- See Also:
ClassResolver.getRegistration(Class)
-
getRegistration
public Registration getRegistration(int classID)
- See Also:
ClassResolver.getRegistration(int)
-
getSerializer
public Serializer getSerializer(Class type)
Returns the serializer for the registration for the specified class.
-
writeClass
public Registration writeClass(Output output, Class type)
Writes a class and returns its registration.- Parameters:
type
- May be null.- Returns:
- Will be null if type is null.
- See Also:
ClassResolver.writeClass(Output, Class)
-
writeObject
public void writeObject(Output output, Object object)
Writes an object using the registered serializer.
-
writeObject
public void writeObject(Output output, Object object, Serializer serializer)
Writes an object using the specified serializer. The registered serializer is ignored.
-
writeObjectOrNull
public void writeObjectOrNull(Output output, Object object, Class type)
Writes an object or null using the registered serializer for the specified type.- Parameters:
object
- May be null.
-
writeObjectOrNull
public void writeObjectOrNull(Output output, Object object, Serializer serializer)
Writes an object or null using the specified serializer. The registered serializer is ignored.- Parameters:
object
- May be null.
-
writeClassAndObject
public void writeClassAndObject(Output output, Object object)
Writes the class and object or null using the registered serializer.- Parameters:
object
- May be null.
-
readClass
public Registration readClass(Input input)
Reads a class and returns its registration.- Returns:
- May be null.
- See Also:
ClassResolver.readClass(Input)
-
readObject
public <T> T readObject(Input input, Class<T> type)
Reads an object using the registered serializer.
-
readObject
public <T> T readObject(Input input, Class<T> type, Serializer serializer)
Reads an object using the specified serializer. The registered serializer is ignored.
-
readObjectOrNull
public <T> T readObjectOrNull(Input input, Class<T> type)
Reads an object or null using the registered serializer.- Returns:
- May be null.
-
readObjectOrNull
public <T> T readObjectOrNull(Input input, Class<T> type, Serializer serializer)
Reads an object or null using the specified serializer. The registered serializer is ignored.- Returns:
- May be null.
-
readClassAndObject
public Object readClassAndObject(Input input)
Reads the class and object or null using the registered serializer.- Returns:
- May be null.
-
reference
public void reference(Object object)
Called bySerializer.read(Kryo, Input, Class)
andSerializer.copy(Kryo, Object)
before Kryo can be used to deserialize or copy child objects. Calling this method is unnecessary if Kryo is not used to deserialize or copy child objects.- Parameters:
object
- May be null, unless calling this method fromSerializer.copy(Kryo, Object)
.
-
reset
public void reset()
Resets object graph state: unregistered class names, references to previously serialized or deserialized objects, theoriginal to copy map
, and thegraph context
. Ifauto reset
is true, this method is called automatically when an object graph has been completely serialized or deserialized. If overridden, the super method must be called.
-
copy
public <T> T copy(T object)
Returns a deep copy of the object. Serializers for the classes involved must supportSerializer.copy(Kryo, Object)
.- Parameters:
object
- May be null.
-
copy
public <T> T copy(T object, Serializer serializer)
Returns a deep copy of the object using the specified serializer. Serializers for the classes involved must supportSerializer.copy(Kryo, Object)
.- Parameters:
object
- May be null.
-
copyShallow
public <T> T copyShallow(T object)
Returns a shallow copy of the object. Serializers for the classes involved must supportSerializer.copy(Kryo, Object)
.- Parameters:
object
- May be null.
-
copyShallow
public <T> T copyShallow(T object, Serializer serializer)
Returns a shallow copy of the object using the specified serializer. Serializers for the classes involved must supportSerializer.copy(Kryo, Object)
.- Parameters:
object
- May be null.
-
getClassResolver
public ClassResolver getClassResolver()
-
getReferenceResolver
public ReferenceResolver getReferenceResolver()
- Returns:
- May be null.
-
setClassLoader
public void setClassLoader(ClassLoader classLoader)
Sets the classloader to resolve unregistered class names to classes. The default is the loader that loaded the Kryo class.
-
getClassLoader
public ClassLoader getClassLoader()
-
setRegistrationRequired
public void setRegistrationRequired(boolean registrationRequired)
If true, an exception is thrown when an unregistered class is encountered. Default is true.If false, when an unregistered class is encountered, its fully qualified class name will be serialized and the
default serializer
for the class used to serialize the object. Subsequent appearances of the class within the same object graph are serialized as an int id.Registered classes are serialized as an int id, avoiding the overhead of serializing the class name, but have the drawback of needing to know the classes to be serialized up front.
Requiring class registeration controls which classes Kryo will instantiate. When false, during deserialization Kryo will invoke the constructor for whatever class name is found in the data. It can be a security problem to allow arbitrary classes to be instantiated (and later finalized).
-
isRegistrationRequired
public boolean isRegistrationRequired()
-
setWarnUnregisteredClasses
public void setWarnUnregisteredClasses(boolean warnUnregisteredClasses)
If true, kryo writes a warn log entry when an unregistered class is encountered. Default is false.
-
getWarnUnregisteredClasses
public boolean getWarnUnregisteredClasses()
-
setReferences
public boolean setReferences(boolean references)
If true, each appearance of an object in the graph after the first is stored as an integer ordinal. This enables references to the same object and cyclic graphs to be serialized, but typically adds overhead of one byte per object. When set to true and noreference resolver
has been set,MapReferenceResolver
is used. Default is false.- Returns:
- The previous value.
-
setCopyReferences
public void setCopyReferences(boolean copyReferences)
If true, whencopy(Object)
and other copy methods encounter an object for the first time the object is copied and on subsequent encounters the copied object is used. If false, the overhead of tracking which objects have already been copied is avoided because each object is copied every time it is encountered, however a stack overflow will occur if an object graph is copied that contains a circular reference. Default is true.
-
setReferenceResolver
public void setReferenceResolver(ReferenceResolver referenceResolver)
Sets the reference resolver and enables references.
-
getReferences
public boolean getReferences()
-
setInstantiatorStrategy
public void setInstantiatorStrategy(org.objenesis.strategy.InstantiatorStrategy strategy)
Sets the strategy used bynewInstantiator(Class)
for creating objects. SeeStdInstantiatorStrategy
to create objects via without calling any constructor. SeeSerializingInstantiatorStrategy
to mimic Java's built-in serialization.- Parameters:
strategy
- May be null.
-
getInstantiatorStrategy
public org.objenesis.strategy.InstantiatorStrategy getInstantiatorStrategy()
-
newInstantiator
protected org.objenesis.instantiator.ObjectInstantiator newInstantiator(Class type)
Returns a new instantiator for creating new instances of the specified type. By default, an instantiator is returned that uses reflection if the class has a zero argument constructor, an exception is thrown. If astrategy
is set, it will be used instead of throwing an exception.
-
newInstance
public <T> T newInstance(Class<T> type)
Creates a new instance of a class usingRegistration.getInstantiator()
. If the registration's instantiator is null, a new one is set usingnewInstantiator(Class)
.
-
getContext
public ObjectMap getContext()
Name/value pairs that are available to all serializers.
-
getGraphContext
public ObjectMap getGraphContext()
Name/value pairs that are available to all serializers and are cleared after each object graph is serialized or deserialized.
-
getDepth
public int getDepth()
Returns the number of child objects away from the object graph root.
-
getOriginalToCopyMap
public IdentityMap getOriginalToCopyMap()
Returns the internal map of original to copy objects when a copy method is used. This can be used after a copy to map old objects to the copies, however it is cleared automatically byreset()
so this is only useful whensetAutoReset(boolean)
is false.
-
setAutoReset
public void setAutoReset(boolean autoReset)
-
setMaxDepth
public void setMaxDepth(int maxDepth)
Sets the maxiumum depth of an object graph. This can be used to prevent malicious data from causing a stack overflow. Default isInteger.MAX_VALUE
.
-
isFinal
public boolean isFinal(Class type)
Returns true if the specified type is final. Final types can be serialized more efficiently because they are non-polymorphic..This can be overridden to force non-final classes to be treated as final. Eg, if an application uses ArrayList extensively but never uses an ArrayList subclass, treating ArrayList as final could allow FieldSerializer to save 1-2 bytes per ArrayList field.
-
isClosure
public boolean isClosure(Class type)
Returns true if the specified type is a closure. When true, Kryo usesClosureSerializer.Closure
instead of the specified type to find the classRegistration
.This can be overridden to support alternative closure implementations. The default implementation returns true if the specified type's name contains '/' (to detect a Java 8+ closure).
-
getGenerics
public Generics getGenerics()
Tracks the generic type arguments and actual classes for type variables in the object graph during seralization.When serializing a type with a single type parameter,
nextGenericClass
will return the generic class (or null) and must be followed bypopGenericType
. SeeCollectionSerializer
for an example.When serializing a type with multiple type parameters,
nextGenericTypes
will return an array ofGenerics.GenericType
, then for each of thoseresolve
returns the generic class. This must be followed bypopGenericType
. SeeMapSerializer
for an example.Generics.GenericsHierarchy
stores the type parameters for a class.pushTypeVariables
can be called before generic types areresolved
so the type parameters are tracked as serialization moved through the object graph. If >0 is returned, this must be followed bypopTypeVariables
. SeeFieldSerializer
for an example.
-
setOptimizedGenerics
public void setOptimizedGenerics(boolean optimizedGenerics)
If true (the default), Kryo attempts to use generic type information to optimize the serialized size. If an object's generic type can be inferred, serializers do not need to write the object's class.Disabling generics optimization can increase performance at the cost of a larger serialized size.
Note that this setting affects the (de)serialization stream, i.e. the serializer and the deserializer need to use the same setting in order to be compatible.
- Parameters:
optimizedGenerics
- whether to optimize generics (default is true)
-
-