/
Kryo.java
1281 lines (1163 loc) · 54.6 KB
/
Kryo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2008, Nathan Sweet
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* - Neither the name of Esoteric Software nor the names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
package com.esotericsoftware.kryo;
import static com.esotericsoftware.kryo.util.Util.*;
import static com.esotericsoftware.minlog.Log.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Currency;
import java.util.Date;
import java.util.EnumSet;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import org.objenesis.instantiator.ObjectInstantiator;
import org.objenesis.strategy.InstantiatorStrategy;
import org.objenesis.strategy.SerializingInstantiatorStrategy;
import org.objenesis.strategy.StdInstantiatorStrategy;
import com.esotericsoftware.kryo.factories.PseudoSerializerFactory;
import com.esotericsoftware.kryo.factories.ReflectionSerializerFactory;
import com.esotericsoftware.kryo.factories.SerializerFactory;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.CollectionSerializer;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.BooleanArraySerializer;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.ByteArraySerializer;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.CharArraySerializer;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.DoubleArraySerializer;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.FloatArraySerializer;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.IntArraySerializer;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.LongArraySerializer;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.ObjectArraySerializer;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.ShortArraySerializer;
import com.esotericsoftware.kryo.serializers.DefaultArraySerializers.StringArraySerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.BigDecimalSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.BigIntegerSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.BooleanSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.ByteSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.CalendarSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.CharSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.ClassSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsEmptyListSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsEmptyMapSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsEmptySetSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsSingletonListSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsSingletonMapSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.CollectionsSingletonSetSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.CurrencySerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.DateSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.DoubleSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.EnumSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.EnumSetSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.FloatSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.IntSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.KryoSerializableSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.LocaleSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.LongSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.ShortSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.StringBufferSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.StringBuilderSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.StringSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.TimeZoneSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.TreeMapSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.TreeSetSerializer;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.VoidSerializer;
import com.esotericsoftware.kryo.serializers.FieldSerializer;
import com.esotericsoftware.kryo.serializers.MapSerializer;
import com.esotericsoftware.kryo.util.DefaultClassResolver;
import com.esotericsoftware.kryo.util.DefaultStreamFactory;
import com.esotericsoftware.kryo.util.IdentityMap;
import com.esotericsoftware.kryo.util.IntArray;
import com.esotericsoftware.kryo.util.MapReferenceResolver;
import com.esotericsoftware.kryo.util.ObjectMap;
import com.esotericsoftware.kryo.util.Util;
import com.esotericsoftware.reflectasm.ConstructorAccess;
/** Maps classes to serializers so object graphs can be serialized automatically.
* @author Nathan Sweet <misc@n4te.com> */
public class Kryo {
static public final byte NULL = 0;
static public final byte NOT_NULL = 1;
static private final int REF = -1;
static private final int NO_REF = -2;
private SerializerFactory defaultSerializer = new ReflectionSerializerFactory(FieldSerializer.class);
private final ArrayList<DefaultSerializerEntry> defaultSerializers = new ArrayList(32);
private final int lowPriorityDefaultSerializerCount;
private final ClassResolver classResolver;
private int nextRegisterID;
private ClassLoader classLoader = getClass().getClassLoader();
private InstantiatorStrategy strategy = new DefaultInstantiatorStrategy();
private boolean registrationRequired;
private int depth, maxDepth = Integer.MAX_VALUE;
private boolean autoReset = true;
private volatile Thread thread;
private ObjectMap context, graphContext;
private ReferenceResolver referenceResolver;
private final IntArray readReferenceIds = new IntArray(0);
private boolean references, copyReferences = true;
private Object readObject;
private int copyDepth;
private boolean copyShallow;
private IdentityMap originalToCopy;
private Object needsCopyReference;
private Generics genericsScope;
/** Tells if ASM-based backend should be used by new serializer instances created using this Kryo instance. */
private boolean asmEnabled = false;
private StreamFactory streamFactory;
/** Creates a new Kryo with a {@link DefaultClassResolver} and a {@link MapReferenceResolver}. */
public Kryo () {
this(new DefaultClassResolver(), new MapReferenceResolver(), new DefaultStreamFactory());
}
/** Creates a new Kryo with a {@link DefaultClassResolver}.
* @param referenceResolver May be null to disable references. */
public Kryo (ReferenceResolver referenceResolver) {
this(new DefaultClassResolver(), referenceResolver, new DefaultStreamFactory());
}
/** @param referenceResolver May be null to disable references. */
public Kryo (ClassResolver classResolver, ReferenceResolver referenceResolver) {
this(classResolver, referenceResolver, new DefaultStreamFactory());
}
/** @param referenceResolver May be null to disable references. */
public Kryo (ClassResolver classResolver, ReferenceResolver referenceResolver, StreamFactory streamFactory) {
if (classResolver == null) throw new IllegalArgumentException("classResolver cannot be null.");
this.classResolver = classResolver;
classResolver.setKryo(this);
this.streamFactory = streamFactory;
streamFactory.setKryo(this);
this.referenceResolver = referenceResolver;
if (referenceResolver != null) {
referenceResolver.setKryo(this);
references = true;
}
addDefaultSerializer(byte[].class, ByteArraySerializer.class);
addDefaultSerializer(char[].class, CharArraySerializer.class);
addDefaultSerializer(short[].class, ShortArraySerializer.class);
addDefaultSerializer(int[].class, IntArraySerializer.class);
addDefaultSerializer(long[].class, LongArraySerializer.class);
addDefaultSerializer(float[].class, FloatArraySerializer.class);
addDefaultSerializer(double[].class, DoubleArraySerializer.class);
addDefaultSerializer(boolean[].class, BooleanArraySerializer.class);
addDefaultSerializer(String[].class, StringArraySerializer.class);
addDefaultSerializer(Object[].class, ObjectArraySerializer.class);
addDefaultSerializer(KryoSerializable.class, KryoSerializableSerializer.class);
addDefaultSerializer(BigInteger.class, BigIntegerSerializer.class);
addDefaultSerializer(BigDecimal.class, BigDecimalSerializer.class);
addDefaultSerializer(Class.class, ClassSerializer.class);
addDefaultSerializer(Date.class, DateSerializer.class);
addDefaultSerializer(Enum.class, EnumSerializer.class);
addDefaultSerializer(EnumSet.class, EnumSetSerializer.class);
addDefaultSerializer(Currency.class, CurrencySerializer.class);
addDefaultSerializer(StringBuffer.class, StringBufferSerializer.class);
addDefaultSerializer(StringBuilder.class, StringBuilderSerializer.class);
addDefaultSerializer(Collections.EMPTY_LIST.getClass(), CollectionsEmptyListSerializer.class);
addDefaultSerializer(Collections.EMPTY_MAP.getClass(), CollectionsEmptyMapSerializer.class);
addDefaultSerializer(Collections.EMPTY_SET.getClass(), CollectionsEmptySetSerializer.class);
addDefaultSerializer(Collections.singletonList(null).getClass(), CollectionsSingletonListSerializer.class);
addDefaultSerializer(Collections.singletonMap(null, null).getClass(), CollectionsSingletonMapSerializer.class);
addDefaultSerializer(Collections.singleton(null).getClass(), CollectionsSingletonSetSerializer.class);
addDefaultSerializer(TreeSet.class, TreeSetSerializer.class);
addDefaultSerializer(Collection.class, CollectionSerializer.class);
addDefaultSerializer(TreeMap.class, TreeMapSerializer.class);
addDefaultSerializer(Map.class, MapSerializer.class);
addDefaultSerializer(TimeZone.class, TimeZoneSerializer.class);
addDefaultSerializer(Calendar.class, CalendarSerializer.class);
addDefaultSerializer(Locale.class, LocaleSerializer.class);
lowPriorityDefaultSerializerCount = defaultSerializers.size();
// Primitives and string. Primitive wrappers automatically use the same registration as primitives.
register(int.class, new IntSerializer());
register(String.class, new StringSerializer());
register(float.class, new FloatSerializer());
register(boolean.class, new BooleanSerializer());
register(byte.class, new ByteSerializer());
register(char.class, new CharSerializer());
register(short.class, new ShortSerializer());
register(long.class, new LongSerializer());
register(double.class, new DoubleSerializer());
register(void.class, new VoidSerializer());
}
// --- Default serializers ---
/** Sets the serializer factory to use when no {@link #addDefaultSerializer(Class, Class) default serializers} match an object's
* type. Default is {@link ReflectionSerializerFactory} with {@link FieldSerializer}.
* @see #newDefaultSerializer(Class) */
public void setDefaultSerializer (SerializerFactory serializer) {
if (serializer == null) throw new IllegalArgumentException("serializer cannot be null.");
defaultSerializer = serializer;
}
/** Sets the serializer to use when no {@link #addDefaultSerializer(Class, Class) default serializers} match an object's type.
* Default is {@link FieldSerializer}.
* @see #newDefaultSerializer(Class) */
public void setDefaultSerializer (Class<? extends Serializer> serializer) {
if (serializer == null) throw new IllegalArgumentException("serializer cannot be null.");
defaultSerializer = new ReflectionSerializerFactory(serializer);
}
/** Instances of the specified class will use the specified serializer when {@link #register(Class)} or
* {@link #register(Class, int)} are called.
* @see #setDefaultSerializer(Class) */
public void addDefaultSerializer (Class type, Serializer serializer) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (serializer == null) throw new IllegalArgumentException("serializer cannot be null.");
DefaultSerializerEntry entry = new DefaultSerializerEntry(type, new PseudoSerializerFactory(serializer));
defaultSerializers.add(defaultSerializers.size() - lowPriorityDefaultSerializerCount, entry);
}
/** Instances of the specified class will use the specified factory to create a serializer when {@link #register(Class)} or
* {@link #register(Class, int)} are called.
* @see #setDefaultSerializer(Class) */
public void addDefaultSerializer (Class type, SerializerFactory serializerFactory) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (serializerFactory == null) throw new IllegalArgumentException("serializerFactory cannot be null.");
DefaultSerializerEntry entry = new DefaultSerializerEntry(type, serializerFactory);
defaultSerializers.add(defaultSerializers.size() - lowPriorityDefaultSerializerCount, entry);
}
/** Instances of the specified class will use the specified serializer when {@link #register(Class)} or
* {@link #register(Class, int)} are called. Serializer instances are created as needed via
* {@link ReflectionSerializerFactory#makeSerializer(Kryo, Class, Class)}. By default, the following classes have a default
* serializer set:
* <p>
* <table>
* <tr>
* <td>boolean</td>
* <td>Boolean</td>
* <td>byte</td>
* <td>Byte</td>
* <td>char</td>
* <tr>
* </tr>
* <td>Character</td>
* <td>short</td>
* <td>Short</td>
* <td>int</td>
* <td>Integer</td>
* <tr>
* </tr>
* <td>long</td>
* <td>Long</td>
* <td>float</td>
* <td>Float</td>
* <td>double</td>
* <tr>
* </tr>
* <td>Double</td>
* <td>String</td>
* <td>byte[]</td>
* <td>char[]</td>
* <td>short[]</td>
* <tr>
* </tr>
* <td>int[]</td>
* <td>long[]</td>
* <td>float[]</td>
* <td>double[]</td>
* <td>String[]</td>
* <tr>
* </tr>
* <td>Object[]</td>
* <td>Map</td>
* <td>BigInteger</td>
* <td>BigDecimal</td>
* <td>KryoSerializable</td>
* </tr>
* <tr>
* <td>Collection</td>
* <td>Date</td>
* <td>Collections.emptyList</td>
* <td>Collections.singleton</td>
* <td>Currency</td>
* </tr>
* <tr>
* <td>StringBuilder</td>
* <td>Enum</td>
* <td>Collections.emptyMap</td>
* <td>Collections.emptySet</td>
* <td>Calendar</td>
* </tr>
* <tr>
* <td>StringBuffer</td>
* <td>Class</td>
* <td>Collections.singletonList</td>
* <td>Collections.singletonMap</td>
* <td>TimeZone</td>
* </tr>
* <tr>
* <td>TreeMap</td>
* <td>EnumSet</td>
* </tr>
* </table>
* <p>
* Note that the order default serializers are added is important for a class that may match multiple types. The above default
* serializers always have a lower priority than subsequent default serializers that are added. */
public void addDefaultSerializer (Class type, Class<? extends Serializer> serializerClass) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (serializerClass == null) throw new IllegalArgumentException("serializerClass cannot be null.");
DefaultSerializerEntry entry = new DefaultSerializerEntry(type, new ReflectionSerializerFactory(serializerClass));
defaultSerializers.add(defaultSerializers.size() - lowPriorityDefaultSerializerCount, entry);
}
/** Returns the best matching serializer for a class. This method can be overridden to implement custom logic to choose a
* serializer. */
public Serializer getDefaultSerializer (Class type) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
final Serializer serializerForAnnotation = getDefaultSerializerForAnnotatedType(type);
if (serializerForAnnotation != null) return serializerForAnnotation;
for (int i = 0, n = defaultSerializers.size(); i < n; i++) {
DefaultSerializerEntry entry = defaultSerializers.get(i);
if (entry.type.isAssignableFrom(type)) {
Serializer defaultSerializer = entry.serializerFactory.makeSerializer(this, type);
return defaultSerializer;
}
}
return newDefaultSerializer(type);
}
protected Serializer getDefaultSerializerForAnnotatedType (Class type) {
if (type.isAnnotationPresent(DefaultSerializer.class)) {
DefaultSerializer defaultSerializerAnnotation = (DefaultSerializer)type.getAnnotation(DefaultSerializer.class);
return ReflectionSerializerFactory.makeSerializer(this, defaultSerializerAnnotation.value(), type);
}
return null;
}
/** Called by {@link #getDefaultSerializer(Class)} when no default serializers matched the type. Subclasses can override this
* method to customize behavior. The default implementation calls {@link SerializerFactory#makeSerializer(Kryo, Class)} using
* the {@link #setDefaultSerializer(Class) default serializer}. */
protected Serializer newDefaultSerializer (Class type) {
return defaultSerializer.makeSerializer(this, type);
}
// --- Registration ---
/** Registers the class using the lowest, next available integer ID and the {@link Kryo#getDefaultSerializer(Class) default
* 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.
* <p>
* 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. */
public Registration register (Class type) {
Registration registration = classResolver.getRegistration(type);
if (registration != null) return registration;
return register(type, getDefaultSerializer(type));
}
/** Registers the class using the specified ID and the {@link Kryo#getDefaultSerializer(Class) default 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.
* <p>
* IDs must be the same at deserialization as they were for serialization.
* @param 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. */
public Registration register (Class type, int id) {
Registration registration = classResolver.getRegistration(type);
if (registration != null) return registration;
return register(type, getDefaultSerializer(type), id);
}
/** 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.
* <p>
* 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. */
public Registration register (Class type, Serializer serializer) {
Registration registration = classResolver.getRegistration(type);
if (registration != null) {
registration.setSerializer(serializer);
return registration;
}
return classResolver.register(new Registration(type, serializer, getNextRegistrationId()));
}
/** 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.
* <p>
* IDs must be the same at deserialization as they were for serialization.
* @param 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. */
public Registration register (Class type, Serializer serializer, int id) {
if (id < 0) throw new IllegalArgumentException("id must be >= 0: " + id);
return register(new Registration(type, serializer, id));
}
/** 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.
* <p>
* IDs must be the same at deserialization as they were for serialization.
* <p>
* Registration can be suclassed to efficiently store per type information, accessible in serializers via
* {@link Kryo#getRegistration(Class)}. */
public Registration register (Registration registration) {
int id = registration.getId();
if (id < 0) throw new IllegalArgumentException("id must be > 0: " + id);
Registration existing = getRegistration(registration.getId());
if (DEBUG && existing != null && existing.getType() != registration.getType()) {
debug("An existing registration with a different type already uses ID: " + registration.getId()
+ "\nExisting registration: " + existing + "\nUnable to set registration: " + registration);
}
return classResolver.register(registration);
}
/** Returns the lowest, next available integer ID. */
public int getNextRegistrationId () {
while (nextRegisterID != -2) {
if (classResolver.getRegistration(nextRegisterID) == null) return nextRegisterID;
nextRegisterID++;
}
throw new KryoException("No registration IDs are available.");
}
/** If the class is not registered and {@link Kryo#setRegistrationRequired(boolean)} is false, it is automatically registered
* using the {@link Kryo#addDefaultSerializer(Class, Class) default serializer}.
* @throws IllegalArgumentException if the class is not registered and {@link Kryo#setRegistrationRequired(boolean)} is true.
* @see ClassResolver#getRegistration(Class) */
public Registration getRegistration (Class type) {
if (type == null) throw new IllegalArgumentException("type cannot be null.");
Registration registration = classResolver.getRegistration(type);
if (registration == null) {
if (Proxy.isProxyClass(type)) {
// If a Proxy class, treat it like an InvocationHandler because the concrete class for a proxy is generated.
registration = getRegistration(InvocationHandler.class);
} else if (!type.isEnum() && Enum.class.isAssignableFrom(type)) {
// This handles an enum value that is an inner class. Eg: enum A {b{}};
registration = getRegistration(type.getEnclosingClass());
} else if (EnumSet.class.isAssignableFrom(type)) {
registration = classResolver.getRegistration(EnumSet.class);
} else if (isClousre(type)) {
registration = classResolver.getRegistration(Closure.class);
}
if (registration == null) {
if (registrationRequired) {
throw new IllegalArgumentException("Class is not registered: " + className(type)
+ "\nNote: To register this class use: kryo.register(" + className(type) + ".class);");
}
registration = classResolver.registerImplicit(type);
}
}
return registration;
}
/** @see ClassResolver#getRegistration(int) */
public Registration getRegistration (int classID) {
return classResolver.getRegistration(classID);
}
/** Returns the serializer for the registration for the specified class.
* @see #getRegistration(Class)
* @see Registration#getSerializer() */
public Serializer getSerializer (Class type) {
return getRegistration(type).getSerializer();
}
// --- Serialization ---
/** Writes a class and returns its registration.
* @param type May be null.
* @return Will be null if type is null.
* @see ClassResolver#writeClass(Output, Class) */
public Registration writeClass (Output output, Class type) {
if (output == null) throw new IllegalArgumentException("output cannot be null.");
try {
return classResolver.writeClass(output, type);
} finally {
if (depth == 0 && autoReset) reset();
}
}
/** Writes an object using the registered serializer. */
public void writeObject (Output output, Object object) {
if (output == null) throw new IllegalArgumentException("output cannot be null.");
if (object == null) throw new IllegalArgumentException("object cannot be null.");
beginObject();
try {
if (references && writeReferenceOrNull(output, object, false)) {
getRegistration(object.getClass()).getSerializer().setGenerics(this, null);
return;
}
if (TRACE || (DEBUG && depth == 1)) log("Write", object);
getRegistration(object.getClass()).getSerializer().write(this, output, object);
} finally {
if (--depth == 0 && autoReset) reset();
}
}
/** Writes an object using the specified serializer. The registered serializer is ignored. */
public void writeObject (Output output, Object object, Serializer serializer) {
if (output == null) throw new IllegalArgumentException("output cannot be null.");
if (object == null) throw new IllegalArgumentException("object cannot be null.");
if (serializer == null) throw new IllegalArgumentException("serializer cannot be null.");
beginObject();
try {
if (references && writeReferenceOrNull(output, object, false)) {
serializer.setGenerics(this, null);
return;
}
if (TRACE || (DEBUG && depth == 1)) log("Write", object);
serializer.write(this, output, object);
} finally {
if (--depth == 0 && autoReset) reset();
}
}
/** Writes an object or null using the registered serializer for the specified type.
* @param object May be null. */
public void writeObjectOrNull (Output output, Object object, Class type) {
if (output == null) throw new IllegalArgumentException("output cannot be null.");
beginObject();
try {
Serializer serializer = getRegistration(type).getSerializer();
if (references) {
if (writeReferenceOrNull(output, object, true)) {
serializer.setGenerics(this, null);
return;
}
} else if (!serializer.getAcceptsNull()) {
if (object == null) {
if (TRACE || (DEBUG && depth == 1)) log("Write", object);
output.writeByte(NULL);
return;
}
output.writeByte(NOT_NULL);
}
if (TRACE || (DEBUG && depth == 1)) log("Write", object);
serializer.write(this, output, object);
} finally {
if (--depth == 0 && autoReset) reset();
}
}
/** Writes an object or null using the specified serializer. The registered serializer is ignored.
* @param object May be null. */
public void writeObjectOrNull (Output output, Object object, Serializer serializer) {
if (output == null) throw new IllegalArgumentException("output cannot be null.");
if (serializer == null) throw new IllegalArgumentException("serializer cannot be null.");
beginObject();
try {
if (references) {
if (writeReferenceOrNull(output, object, true)) {
serializer.setGenerics(this, null);
return;
}
} else if (!serializer.getAcceptsNull()) {
if (object == null) {
if (TRACE || (DEBUG && depth == 1)) log("Write", null);
output.writeByte(NULL);
return;
}
output.writeByte(NOT_NULL);
}
if (TRACE || (DEBUG && depth == 1)) log("Write", object);
serializer.write(this, output, object);
} finally {
if (--depth == 0 && autoReset) reset();
}
}
/** Writes the class and object or null using the registered serializer.
* @param object May be null. */
public void writeClassAndObject (Output output, Object object) {
if (output == null) throw new IllegalArgumentException("output cannot be null.");
beginObject();
try {
if (object == null) {
writeClass(output, null);
return;
}
Registration registration = writeClass(output, object.getClass());
if (references && writeReferenceOrNull(output, object, false)) {
registration.getSerializer().setGenerics(this, null);
return;
}
if (TRACE || (DEBUG && depth == 1)) log("Write", object);
registration.getSerializer().write(this, output, object);
} finally {
if (--depth == 0 && autoReset) reset();
}
}
/** @param object May be null if mayBeNull is true.
* @return true if no bytes need to be written for the object. */
boolean writeReferenceOrNull (Output output, Object object, boolean mayBeNull) {
if (object == null) {
if (TRACE || (DEBUG && depth == 1)) log("Write", null);
output.writeVarInt(Kryo.NULL, true);
return true;
}
if (!referenceResolver.useReferences(object.getClass())) {
if (mayBeNull) output.writeVarInt(Kryo.NOT_NULL, true);
return false;
}
// Determine if this object has already been seen in this object graph.
int id = referenceResolver.getWrittenId(object);
// If not the first time encountered, only write reference ID.
if (id != -1) {
if (DEBUG) debug("kryo", "Write object reference " + id + ": " + string(object));
output.writeVarInt(id + 2, true); // + 2 because 0 and 1 are used for NULL and NOT_NULL.
return true;
}
// Otherwise write NOT_NULL and then the object bytes.
id = referenceResolver.addWrittenObject(object);
output.writeVarInt(NOT_NULL, true);
if (TRACE) trace("kryo", "Write initial object reference " + id + ": " + string(object));
return false;
}
/** Reads a class and returns its registration.
* @return May be null.
* @see ClassResolver#readClass(Input) */
public Registration readClass (Input input) {
if (input == null) throw new IllegalArgumentException("input cannot be null.");
try {
return classResolver.readClass(input);
} finally {
if (depth == 0 && autoReset) reset();
}
}
/** Reads an object using the registered serializer. */
public <T> T readObject (Input input, Class<T> type) {
if (input == null) throw new IllegalArgumentException("input cannot be null.");
if (type == null) throw new IllegalArgumentException("type cannot be null.");
beginObject();
try {
T object;
if (references) {
int stackSize = readReferenceOrNull(input, type, false);
if (stackSize == REF) return (T)readObject;
object = (T)getRegistration(type).getSerializer().read(this, input, type);
if (stackSize == readReferenceIds.size) reference(object);
} else
object = (T)getRegistration(type).getSerializer().read(this, input, type);
if (TRACE || (DEBUG && depth == 1)) log("Read", object);
return object;
} finally {
if (--depth == 0 && autoReset) reset();
}
}
/** Reads an object using the specified serializer. The registered serializer is ignored. */
public <T> T readObject (Input input, Class<T> type, Serializer serializer) {
if (input == null) throw new IllegalArgumentException("input cannot be null.");
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (serializer == null) throw new IllegalArgumentException("serializer cannot be null.");
beginObject();
try {
T object;
if (references) {
int stackSize = readReferenceOrNull(input, type, false);
if (stackSize == REF) return (T)readObject;
object = (T)serializer.read(this, input, type);
if (stackSize == readReferenceIds.size) reference(object);
} else
object = (T)serializer.read(this, input, type);
if (TRACE || (DEBUG && depth == 1)) log("Read", object);
return object;
} finally {
if (--depth == 0 && autoReset) reset();
}
}
/** Reads an object or null using the registered serializer.
* @return May be null. */
public <T> T readObjectOrNull (Input input, Class<T> type) {
if (input == null) throw new IllegalArgumentException("input cannot be null.");
if (type == null) throw new IllegalArgumentException("type cannot be null.");
beginObject();
try {
T object;
if (references) {
int stackSize = readReferenceOrNull(input, type, true);
if (stackSize == REF) return (T)readObject;
object = (T)getRegistration(type).getSerializer().read(this, input, type);
if (stackSize == readReferenceIds.size) reference(object);
} else {
Serializer serializer = getRegistration(type).getSerializer();
if (!serializer.getAcceptsNull() && input.readByte() == NULL) {
if (TRACE || (DEBUG && depth == 1)) log("Read", null);
return null;
}
object = (T)serializer.read(this, input, type);
}
if (TRACE || (DEBUG && depth == 1)) log("Read", object);
return object;
} finally {
if (--depth == 0 && autoReset) reset();
}
}
/** Reads an object or null using the specified serializer. The registered serializer is ignored.
* @return May be null. */
public <T> T readObjectOrNull (Input input, Class<T> type, Serializer serializer) {
if (input == null) throw new IllegalArgumentException("input cannot be null.");
if (type == null) throw new IllegalArgumentException("type cannot be null.");
if (serializer == null) throw new IllegalArgumentException("serializer cannot be null.");
beginObject();
try {
T object;
if (references) {
int stackSize = readReferenceOrNull(input, type, true);
if (stackSize == REF) return (T)readObject;
object = (T)serializer.read(this, input, type);
if (stackSize == readReferenceIds.size) reference(object);
} else {
if (!serializer.getAcceptsNull() && input.readByte() == NULL) {
if (TRACE || (DEBUG && depth == 1)) log("Read", null);
return null;
}
object = (T)serializer.read(this, input, type);
}
if (TRACE || (DEBUG && depth == 1)) log("Read", object);
return object;
} finally {
if (--depth == 0 && autoReset) reset();
}
}
/** Reads the class and object or null using the registered serializer.
* @return May be null. */
public Object readClassAndObject (Input input) {
if (input == null) throw new IllegalArgumentException("input cannot be null.");
beginObject();
try {
Registration registration = readClass(input);
if (registration == null) return null;
Class type = registration.getType();
Object object;
if (references) {
registration.getSerializer().setGenerics(this, null);
int stackSize = readReferenceOrNull(input, type, false);
if (stackSize == REF) return readObject;
object = registration.getSerializer().read(this, input, type);
if (stackSize == readReferenceIds.size) reference(object);
} else
object = registration.getSerializer().read(this, input, type);
if (TRACE || (DEBUG && depth == 1)) log("Read", object);
return object;
} finally {
if (--depth == 0 && autoReset) reset();
}
}
/** Returns {@link #REF} if a reference to a previously read object was read, which is stored in {@link #readObject}. Returns a
* stack size (> 0) if a reference ID has been put on the stack. */
int readReferenceOrNull (Input input, Class type, boolean mayBeNull) {
if (type.isPrimitive()) type = getWrapperClass(type);
boolean referencesSupported = referenceResolver.useReferences(type);
int id;
if (mayBeNull) {
id = input.readVarInt(true);
if (id == Kryo.NULL) {
if (TRACE || (DEBUG && depth == 1)) log("Read", null);
readObject = null;
return REF;
}
if (!referencesSupported) {
readReferenceIds.add(NO_REF);
return readReferenceIds.size;
}
} else {
if (!referencesSupported) {
readReferenceIds.add(NO_REF);
return readReferenceIds.size;
}
id = input.readVarInt(true);
}
if (id == NOT_NULL) {
// First time object has been encountered.
id = referenceResolver.nextReadId(type);
if (TRACE) trace("kryo", "Read initial object reference " + id + ": " + className(type));
readReferenceIds.add(id);
return readReferenceIds.size;
}
// The id is an object reference.
id -= 2; // - 2 because 0 and 1 are used for NULL and NOT_NULL.
readObject = referenceResolver.getReadObject(type, id);
if (DEBUG) debug("kryo", "Read object reference " + id + ": " + string(readObject));
return REF;
}
/** Called by {@link Serializer#read(Kryo, Input, Class)} and {@link Serializer#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.
* @param object May be null, unless calling this method from {@link Serializer#copy(Kryo, Object)}. */
public void reference (Object object) {
if (copyDepth > 0) {
if (needsCopyReference != null) {
if (object == null) throw new IllegalArgumentException("object cannot be null.");
originalToCopy.put(needsCopyReference, object);
needsCopyReference = null;
}
} else if (references && object != null) {
int id = readReferenceIds.pop();
if (id != NO_REF) referenceResolver.setReadObject(id, object);
}
}
/** Resets unregistered class names, references to previously serialized or deserialized objects, and the
* {@link #getGraphContext() graph context}. If {@link #setAutoReset(boolean) auto 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. */
public void reset () {
depth = 0;
if (graphContext != null) graphContext.clear();
classResolver.reset();
if (references) {
referenceResolver.reset();
readObject = null;
}
copyDepth = 0;
if (originalToCopy != null) originalToCopy.clear(2048);
if (TRACE) trace("kryo", "Object graph complete.");
}
/** Returns a deep copy of the object. Serializers for the classes involved must support {@link Serializer#copy(Kryo, Object)}.
* @param object May be null. */
public <T> T copy (T object) {
if (object == null) return null;
if (copyShallow) return object;
copyDepth++;
try {
if (originalToCopy == null) originalToCopy = new IdentityMap();
Object existingCopy = originalToCopy.get(object);
if (existingCopy != null) return (T)existingCopy;
if (copyReferences) needsCopyReference = object;
Object copy;
if (object instanceof KryoCopyable)
copy = ((KryoCopyable)object).copy(this);
else
copy = getSerializer(object.getClass()).copy(this, object);
if (needsCopyReference != null) reference(copy);
if (TRACE || (DEBUG && copyDepth == 1)) log("Copy", copy);
return (T)copy;
} finally {
if (--copyDepth == 0) reset();
}
}
/** Returns a deep copy of the object using the specified serializer. Serializers for the classes involved must support
* {@link Serializer#copy(Kryo, Object)}.
* @param object May be null. */
public <T> T copy (T object, Serializer serializer) {
if (object == null) return null;
if (copyShallow) return object;
copyDepth++;
try {
if (originalToCopy == null) originalToCopy = new IdentityMap();
Object existingCopy = originalToCopy.get(object);
if (existingCopy != null) return (T)existingCopy;
if (copyReferences) needsCopyReference = object;
Object copy;
if (object instanceof KryoCopyable)
copy = ((KryoCopyable)object).copy(this);
else
copy = serializer.copy(this, object);
if (needsCopyReference != null) reference(copy);
if (TRACE || (DEBUG && copyDepth == 1)) log("Copy", copy);
return (T)copy;
} finally {
if (--copyDepth == 0) reset();
}
}
/** Returns a shallow copy of the object. Serializers for the classes involved must support
* {@link Serializer#copy(Kryo, Object)}.
* @param object May be null. */
public <T> T copyShallow (T object) {
if (object == null) return null;
copyDepth++;
copyShallow = true;
try {
if (originalToCopy == null) originalToCopy = new IdentityMap();
Object existingCopy = originalToCopy.get(object);
if (existingCopy != null) return (T)existingCopy;
if (copyReferences) needsCopyReference = object;
Object copy;
if (object instanceof KryoCopyable)
copy = ((KryoCopyable)object).copy(this);
else
copy = getSerializer(object.getClass()).copy(this, object);
if (needsCopyReference != null) reference(copy);
if (TRACE || (DEBUG && copyDepth == 1)) log("Shallow copy", copy);
return (T)copy;
} finally {
copyShallow = false;
if (--copyDepth == 0) reset();
}
}
/** Returns a shallow copy of the object using the specified serializer. Serializers for the classes involved must support
* {@link Serializer#copy(Kryo, Object)}.
* @param object May be null. */
public <T> T copyShallow (T object, Serializer serializer) {
if (object == null) return null;
copyDepth++;
copyShallow = true;
try {
if (originalToCopy == null) originalToCopy = new IdentityMap();
Object existingCopy = originalToCopy.get(object);
if (existingCopy != null) return (T)existingCopy;
if (copyReferences) needsCopyReference = object;
Object copy;
if (object instanceof KryoCopyable)
copy = ((KryoCopyable)object).copy(this);
else
copy = serializer.copy(this, object);
if (needsCopyReference != null) reference(copy);
if (TRACE || (DEBUG && copyDepth == 1)) log("Shallow copy", copy);
return (T)copy;
} finally {
copyShallow = false;
if (--copyDepth == 0) reset();
}
}
// --- Utility ---
private void beginObject () {
if (DEBUG) {
if (depth == 0)
thread = Thread.currentThread();
else if (thread != Thread.currentThread())
throw new ConcurrentModificationException("Kryo must not be accessed concurrently by multiple threads.");
}
if (depth == maxDepth) throw new KryoException("Max depth exceeded: " + depth);
depth++;
}
public ClassResolver getClassResolver () {
return classResolver;
}
/** @return May be null. */
public ReferenceResolver getReferenceResolver () {
return referenceResolver;
}