-
Notifications
You must be signed in to change notification settings - Fork 668
/
ObjectStreamClass.java
2733 lines (2333 loc) · 111 KB
/
ObjectStreamClass.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) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import jdk.internal.misc.JavaSecurityAccess;
import jdk.internal.misc.SharedSecrets;
import jdk.internal.misc.Unsafe;
import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.Reflection;
import jdk.internal.reflect.ReflectionFactory;
import sun.reflect.misc.ReflectUtil;
import static java.io.ObjectStreamField.appendClassSignature;
import static java.io.ObjectStreamField.getClassSignature;
/**
* Serialization's descriptor for classes.
* It contains the name and serialVersionUID of the class.
* The ObjectStreamClass for a specific class loaded in this Java VM can be found/created using the lookup method.
*
* <p>The algorithm to compute the SerialVersionUID is described in
* <a href="{@docRoot}/../specs/serialization/class.html#stream-unique-identifiers">
* Object Serialization Specification, Section 4.6, Stream Unique Identifiers</a>.
*
* @author Mike Warres
* @author Roger Riggs
* @see ObjectStreamField
* @see <a href="{@docRoot}/../specs/serialization/class.html">
* Object Serialization Specification, Section 4, Class Descriptors</a>
* @since 1.1
*/
// 待序列化/反序列化对象的序列化描述符
public class ObjectStreamClass implements Serializable {
private static final long serialVersionUID = -6120832682080437368L;
/** serialPersistentFields value indicating no serializable fields */
public static final ObjectStreamField[] NO_FIELDS = new ObjectStreamField[0]; // 表示不存在待序列化的字段
private static final ObjectStreamField[] serialPersistentFields = NO_FIELDS; // 待序列化的字段集,默认指示不存在待序列化字段
/** reflection factory for obtaining serialization constructors */
// 反射对象工厂
private static final ReflectionFactory reflFactory = AccessController.doPrivileged(new ReflectionFactory.GetReflectionFactoryAction());
/** serialVersionUID of represented class (null if not computed yet) */
private volatile Long suid; // cl的序列化编号
/** data layout of serialized objects described by this class desc */
private volatile ClassDataSlot[] dataLayout; // 数据槽:包含从当前类到最上层实现了Serializable接口的父类的所有序列化描述符
/** class associated with this descriptor (if any) */
private Class<?> cl; // 待序列化的类对象
/** name of class represented by this descriptor */
private String name; // cl的类型名称(虚拟机中呈现的名称)
/** true if represents dynamic proxy class */
private boolean isProxy; // cl是否为代理类
/** true if represents enum type */
private boolean isEnum; // cl是否为枚举类
/** true if represented class implements Serializable */
private boolean serializable; // cl是否为Serializable实现类
/** true if represented class implements Externalizable */
private boolean externalizable; // cl是否为Externalizable实现类
/** serializable fields */
private ObjectStreamField[] fields; // 待序列化字段的序列化描述符信息(要求原始类型排在前面,引用类型排在后面)
/** aggregate marshalled size of primitive fields */
private int primDataSize; // 统计fields中基本类型字段所占字节数
/** number of non-primitive fields */
private int numObjFields; // 统计fields中引用类型字段数量
/** reflector for setting/getting serializable field values */
private FieldReflector fieldRefl; // 待序列化的字段的统计信息
/** serialization-appropriate constructor, or null if none */
private Constructor<?> cons; // 生成反序列化对象的构造器
/** protection domains that need to be checked when calling the constructor */
private ProtectionDomain[] domains; // 保护域信息
/** true if desc has data written by class-defined writeObject method */
private boolean hasWriteObjectData; // 当前类中是否包含writeObject方法(Serializable实现类)
/** class-defined writeObject method, or null if none */
private Method writeObjectMethod; // 当前类中的writeObject方法(Serializable实现类)
/** class-defined readObject method, or null if none */
private Method readObjectMethod; // 当前类中的readObject方法(Serializable实现类)
/** class-defined readObjectNoData method, or null if none */
private Method readObjectNoDataMethod; // 当前类中的readObjectNoData方法(Serializable实现类)
/** class-defined writeReplace method, or null if none */
private Method writeReplaceMethod; // 当前类中的writeReplace方法
/** class-defined readResolve method, or null if none */
private Method readResolveMethod; // 当前类中的readResolve方法
/** local class descriptor for represented class (may point to self) */
private ObjectStreamClass localDesc; // cl的序列化描述符
/** superclass descriptor appearing in stream */
private ObjectStreamClass superDesc; // cl的父类的序列化描述符
/** true if, and only if, the object has been correctly initialized */
private boolean initialized; // 序列化描述符信息是否已经完成初始化
/**
* true if desc has externalizable data written in block data format; this
* must be true by default to accommodate ObjectInputStream subclasses which
* override readClassDescriptor() to return class descriptors obtained from
* ObjectStreamClass.lookup() (see 4461737)
*/
private boolean hasBlockExternalData = true; // 是否包含块数据
/** exception (if any) thrown while attempting to resolve class */
private ClassNotFoundException resolveEx;
/** exception (if any) to throw if non-enum serialization attempted */
private ExceptionInfo serializeEx;
/** exception (if any) to throw if non-enum deserialization attempted */
private ExceptionInfo deserializeEx;
/** exception (if any) to throw if default serialization attempted */
private ExceptionInfo defaultSerializeEx;
static {
initNative();
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates blank class descriptor which should be initialized via a subsequent call to initProxy(), initNonProxy() or readNonProxy().
*/
ObjectStreamClass() {
}
/**
* Creates local class descriptor representing given class.
*/
// 为实现序列化接口的类对象创建一个序列化描述符
private ObjectStreamClass(final Class<?> cl) {
// 待序列化的类型
this.cl = cl;
// 待序列化的类型名称(虚拟机中呈现的名称)
name = cl.getName();
// 判断cl是否为代理类
isProxy = Proxy.isProxyClass(cl);
// 判断cl是否为枚举类
isEnum = Enum.class.isAssignableFrom(cl);
// 判断cl是否为Serializable类
serializable = Serializable.class.isAssignableFrom(cl);
// 判断cl是否为Externalizable类
externalizable = Externalizable.class.isAssignableFrom(cl);
// 获取cl的父类
Class<?> superCl = cl.getSuperclass();
// 获取cl的父类对象superCl的序列化描述符(只允许处理Serializable类型的实现类)
superDesc = (superCl != null) ? lookup(superCl, false) : null;
// cl的序列化描述符
localDesc = this;
// 如果cl为Serializable类
if(serializable) {
AccessController.doPrivileged(new PrivilegedAction<>() {
public Void run() {
// 如果cl为枚举类
if(isEnum) {
suid = 0L;
fields = NO_FIELDS;
return null;
}
// 如果cl为数组类
if(cl.isArray()) {
fields = NO_FIELDS;
return null;
}
// 获取cl类型的对象的序列化编号
suid = getDeclaredSUID(cl);
try {
/*
* 返回cl类中待序列化字段的序列化描述符,要求cl类本身满足以下条件才能获取有效字段集:
* 1.是Serializable实现类
* 2.不是代理类
* 3.不是枚举
* 4.不是接口
*/
fields = getSerialFields(cl);
/*
* 统计fields中原始类型字段所占字节数与引用类型字段的数量,
* 并校验fields中的字段顺序(原始类型排在前面,引用类型排在后面)。
*/
computeFieldOffsets();
} catch(InvalidClassException e) {
serializeEx = deserializeEx = new ExceptionInfo(e.classname, e.getMessage());
fields = NO_FIELDS;
}
// 如果cl是Externalizable实现类
if(externalizable) {
// 获取cl类的public无参构造器,如果不存在则返回null
cons = getExternalizableConstructor(cl);
// 如果cl是Serializable实现类
} else {
/*
* 返回cl的第一个不可序列化的父类的无参构造器,要求改无参构造器可被cl访问。
* 如果未找到该构造器,或该构造器子类无法访问,则返回null。
* 对返回的构造函数(如果有)禁用访问检查。
*/
cons = getSerializableConstructor(cl);
// 获取"private void writeObject(ObjectOutputStream out)"方法
writeObjectMethod = getPrivateMethod(cl, "writeObject", new Class<?>[]{ObjectOutputStream.class}, Void.TYPE);
// 获取"private void readObject(ObjectOutputStream out)"方法
readObjectMethod = getPrivateMethod(cl, "readObject", new Class<?>[]{ObjectInputStream.class}, Void.TYPE);
// 获取"private void readObjectNoData()"方法
readObjectNoDataMethod = getPrivateMethod(cl, "readObjectNoData", null, Void.TYPE);
// 是否存在writeObject方法
hasWriteObjectData = (writeObjectMethod != null);
}
// 保护域信息
domains = getProtectionDomains(cons, cl);
// 获取"private Object writeReplace()"方法
writeReplaceMethod = getInheritableMethod(cl, "writeReplace", null, Object.class);
// 获取"private Object readResolve()"方法
readResolveMethod = getInheritableMethod(cl, "readResolve", null, Object.class);
return null;
}
});
} else {
suid = 0L;
fields = NO_FIELDS;
}
try {
// 获取待序列化的字段的统计信息
fieldRefl = getReflector(fields, this);
} catch(InvalidClassException ex) {
// field mismatches impossible when matching local fields vs. self
throw new InternalError(ex);
}
// 反序列化异常
if(deserializeEx == null) {
if(isEnum) {
deserializeEx = new ExceptionInfo(name, "enum type");
} else if(cons == null) {
deserializeEx = new ExceptionInfo(name, "no valid constructor");
}
}
// 遍历待序列化字段的序列化描述符信息
for(ObjectStreamField field : fields) {
// 如果该序列化描述符中存在无效字段
if(field.getField() == null) {
defaultSerializeEx = new ExceptionInfo(name, "unmatched serializable field(s) declared");
}
}
initialized = true;
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Find the descriptor for a class that can be serialized. Creates an
* ObjectStreamClass instance if one does not exist yet for class. Null is
* returned if the specified class does not implement java.io.Serializable
* or java.io.Externalizable.
*
* @param cl class for which to get the descriptor
*
* @return the class descriptor for the specified class
*/
// 获取类对象cl(只允许处理Serializable类型)的序列化描述符,返回之前会先去缓存中查找
public static ObjectStreamClass lookup(Class<?> cl) {
return lookup(cl, false);
}
/**
* Returns the descriptor for any class, regardless of whether it
* implements {@link Serializable}.
*
* @param cl class for which to get the descriptor
*
* @return the class descriptor for the specified class
*
* @since 1.6
*/
// 获取类对象cl的序列化描述符,返回之前会先去缓存中查找
public static ObjectStreamClass lookupAny(Class<?> cl) {
return lookup(cl, true);
}
/**
* Looks up and returns class descriptor for given class, or null if class is non-serializable and "all" is set to false.
*
* @param cl class to look up
* @param all if true, return descriptors for all classes;
* if false, only return descriptors for serializable classes
*/
/*
* 返回类对象cl的序列化描述符,返回之前会先去缓存中查找。
* all为true指示允许处理任意类型,而all为false则指示只允许处理Serializable类型(的实现类)。
*/
static ObjectStreamClass lookup(Class<?> cl, boolean all) {
if(!all && !Serializable.class.isAssignableFrom(cl)) {
return null;
}
// 从localDescs中移除localDescsQueue中包含的元素
processQueue(Caches.localDescsQueue, Caches.localDescs);
// 将指定的类对象包装为弱引用键,并指定localDescsQueue为其引用队列
WeakClassKey key = new WeakClassKey(cl, Caches.localDescsQueue);
// 获取该弱引用键映射的引用
Reference<?> ref = Caches.localDescs.get(key);
Object entry = null;
// 获取key关联的软引用追踪的对象
if(ref != null) {
// 返回此Reference包裹的自定义引用对象,如果该对象已被回收,则返回null
entry = ref.get();
}
EntryFuture future = null;
// 需要将其他获取value的线程阻塞住,等为key关联新value后再放行
if(entry == null) {
EntryFuture newEntry = new EntryFuture();
// 包装了EntryFuture的软引用
Reference<?> newRef = new SoftReference<>(newEntry);
do {
// 之前软引用追踪的对象被回收了
if(ref != null) {
// 从map中移除拥有指定key和value的元素,返回值表示是否移除成功
Caches.localDescs.remove(key, ref);
}
// 重新关联:将指定的元素(key-value)存入Map,并返回旧值,不允许覆盖
ref = Caches.localDescs.putIfAbsent(key, newRef);
// 如果key已经关联值(来自别的线程干扰)
if(ref != null) {
// 获取当前key关联的软引用追踪的对象
entry = ref.get();
}
} while(ref != null && entry == null);
// newEntry被成功关联
if(entry == null) {
future = newEntry;
}
}
// 直接获取到了目标value
if(entry instanceof ObjectStreamClass) { // check common case first
return (ObjectStreamClass) entry;
}
if (entry instanceof EntryFuture) {
future = (EntryFuture) entry;
if(future.getOwner() == Thread.currentThread()) {
/*
* Handle nested call situation described by 4803747: waiting
* for future value to be set by a lookup() call further up the
* stack will result in deadlock, so calculate and set the
* future value here instead.
*/
entry = null;
} else {
// 如果key没有关联到有效的value,会阻塞
entry = future.get();
}
}
if(entry == null) {
try {
// 生成cl类的序列化描述符信息
entry = new ObjectStreamClass(cl);
} catch(Throwable th) {
entry = th;
}
/*
* 此刻,key已经准备好关联有效的value(entry),
* 因此可以唤醒所有阻塞在future.get()上的线程了
*/
if(future.set(entry)) {
// 将指定的元素(key-value)存入Map,并返回旧值,允许覆盖
Caches.localDescs.put(key, new SoftReference<>(entry));
} else {
// nested lookup call already set future
entry = future.get();
}
}
// 正常返回
if(entry instanceof ObjectStreamClass) {
return (ObjectStreamClass) entry;
} else if(entry instanceof RuntimeException) {
throw (RuntimeException) entry;
} else if(entry instanceof Error) {
throw (Error) entry;
} else {
throw new InternalError("unexpected entry: " + entry);
}
}
/*▲ ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Invokes the writeObject method of the represented serializable class.
* Throws UnsupportedOperationException if this class descriptor is not
* associated with a class, or if the class is externalizable,
* non-serializable or does not define writeObject.
*/
// 调用obj对象的writeObject方法(Serializable实现类)
void invokeWriteObject(Object obj, ObjectOutputStream out) throws IOException, UnsupportedOperationException {
requireInitialized();
if(writeObjectMethod != null) {
try {
writeObjectMethod.invoke(obj, out);
} catch(InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if(th instanceof IOException) {
throw (IOException) th;
} else {
throwMiscException(th);
}
} catch(IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError(ex);
}
} else {
throw new UnsupportedOperationException();
}
}
/**
* Invokes the readObject method of the represented serializable class.
* Throws UnsupportedOperationException if this class descriptor is not
* associated with a class, or if the class is externalizable,
* non-serializable or does not define readObject.
*/
// 调用obj对象的readObject方法(Serializable实现类)
void invokeReadObject(Object obj, ObjectInputStream in) throws ClassNotFoundException, IOException, UnsupportedOperationException {
requireInitialized();
if(readObjectMethod != null) {
try {
readObjectMethod.invoke(obj, in);
} catch(InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if(th instanceof ClassNotFoundException) {
throw (ClassNotFoundException) th;
} else if(th instanceof IOException) {
throw (IOException) th;
} else {
throwMiscException(th);
}
} catch(IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError(ex);
}
} else {
throw new UnsupportedOperationException();
}
}
/**
* Invokes the readObjectNoData method of the represented serializable
* class. Throws UnsupportedOperationException if this class descriptor is
* not associated with a class, or if the class is externalizable,
* non-serializable or does not define readObjectNoData.
*/
// 调用obj对象的readObjectNoDataMethod方法(Serializable实现类)
void invokeReadObjectNoData(Object obj) throws IOException, UnsupportedOperationException {
requireInitialized();
if(readObjectNoDataMethod != null) {
try {
readObjectNoDataMethod.invoke(obj, (Object[]) null);
} catch(InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if(th instanceof ObjectStreamException) {
throw (ObjectStreamException) th;
} else {
throwMiscException(th);
}
} catch(IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError(ex);
}
} else {
throw new UnsupportedOperationException();
}
}
/**
* Invokes the writeReplace method of the represented serializable class and returns the result.
* Throws UnsupportedOperationException if this class descriptor is not associated with a class,
* or if the class is non-serializable or does not define writeReplace.
*/
// 调用obj对象的writeReplace方法
Object invokeWriteReplace(Object obj) throws IOException, UnsupportedOperationException {
requireInitialized();
if(writeReplaceMethod != null) {
try {
// 调用writeReplace方法
return writeReplaceMethod.invoke(obj, (Object[]) null);
} catch(InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if(th instanceof ObjectStreamException) {
throw (ObjectStreamException) th;
} else {
throwMiscException(th);
throw new InternalError(th); // never reached
}
} catch(IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError(ex);
}
} else {
throw new UnsupportedOperationException();
}
}
/**
* Invokes the readResolve method of the represented serializable class and
* returns the result. Throws UnsupportedOperationException if this class
* descriptor is not associated with a class, or if the class is
* non-serializable or does not define readResolve.
*/
Object invokeReadResolve(Object obj) throws IOException, UnsupportedOperationException {
requireInitialized();
if(readResolveMethod != null) {
try {
return readResolveMethod.invoke(obj, (Object[]) null);
} catch(InvocationTargetException ex) {
Throwable th = ex.getTargetException();
if(th instanceof ObjectStreamException) {
throw (ObjectStreamException) th;
} else {
throwMiscException(th);
throw new InternalError(th); // never reached
}
} catch(IllegalAccessException ex) {
// should not occur, as access checks have been suppressed
throw new InternalError(ex);
}
} else {
throw new UnsupportedOperationException();
}
}
/*▲ ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns array of ClassDataSlot instances representing the data layout
* (including superclass data) for serialized objects described by this class descriptor.
* ClassDataSlots are ordered by inheritance with those containing "higher" superclasses appearing first.
* The final ClassDataSlot contains a reference to this descriptor.
*/
// 返回数据槽:包含从当前类到最上层实现了Serializable接口的父类的所有序列化描述符
ClassDataSlot[] getClassDataLayout() throws InvalidClassException {
// REMIND: synchronize instead of relying on volatile?
if(dataLayout == null) {
dataLayout = getClassDataLayout0();
}
return dataLayout;
}
// 返回数据槽:包含从当前类到最上层实现了Serializable接口的父类的所有序列化描述符
private ClassDataSlot[] getClassDataLayout0() throws InvalidClassException {
ArrayList<ClassDataSlot> slots = new ArrayList<>();
Class<?> start = cl, end = cl;
/* locate closest non-serializable superclass */
// 查找cl首个非Serializable类型的父类
while(end != null && Serializable.class.isAssignableFrom(end)) {
end = end.getSuperclass();
}
HashSet<String> oscNames = new HashSet<>(3);
for(ObjectStreamClass d = this; d != null; d = d.superDesc) {
if(oscNames.contains(d.name)) {
throw new InvalidClassException("Circular reference.");
} else {
oscNames.add(d.name);
}
/* search up inheritance hierarchy for class with matching name */
String searchName = (d.cl != null) ? d.cl.getName() : d.name;
Class<?> match = null;
for(Class<?> c = start; c != end; c = c.getSuperclass()) {
if(searchName.equals(c.getName())) {
match = c;
break;
}
}
/* add "no data" slot for each unmatched class below match */
if(match != null) {
for(Class<?> c = start; c != match; c = c.getSuperclass()) {
// 获取类对象c的序列化描述符,返回之前会先去缓存中查找
ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(c, true);
ClassDataSlot slot = new ClassDataSlot(objectStreamClass, false);
slots.add(slot);
}
start = match.getSuperclass();
}
// 获取类对象cl的一个序列化描述符
ObjectStreamClass objectStreamClass = d.getVariantFor(match);
ClassDataSlot slot = new ClassDataSlot(objectStreamClass, true);
// record descriptor/class pairing
slots.add(slot);
}
/* add "no data" slot for any leftover unmatched classes */
for(Class<?> c = start; c != end; c = c.getSuperclass()) {
// 获取类对象c的序列化描述符,返回之前会先去缓存中查找
ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(c, true);
ClassDataSlot slot = new ClassDataSlot(objectStreamClass, false);
slots.add(slot);
}
// order slots from superclass -> subclass
Collections.reverse(slots); // 逆转list中的元素:使得父类的序列化描述符排列到前面
return slots.toArray(new ClassDataSlot[slots.size()]);
}
/**
* If given class is the same as the class associated with this class descriptor, returns reference to this class descriptor.
* Otherwise, returns variant of this class descriptor bound to given class.
*/
// 获取类对象cl的一个序列化描述符
private ObjectStreamClass getVariantFor(Class<?> cl) throws InvalidClassException {
if(this.cl == cl) {
return this;
}
ObjectStreamClass desc = new ObjectStreamClass();
if(isProxy) {
// 使用代理类对象cl来初始化desc
desc.initProxy(cl, null, superDesc);
} else {
// 使用非代理类对象cl来初始化desc
desc.initNonProxy(this, cl, null, superDesc);
}
return desc;
}
/**
* Initializes class descriptor representing a proxy class.
*/
// 使用代理类对象cl来初始化当前序列化描述符
void initProxy(Class<?> cl, ClassNotFoundException resolveEx, ObjectStreamClass superDesc) throws InvalidClassException {
ObjectStreamClass osc = null;
if(cl != null) {
// 获取类对象cl的序列化描述符,返回之前会先去缓存中查找
osc = lookup(cl, true);
if(!osc.isProxy) {
throw new InvalidClassException("cannot bind proxy descriptor to a non-proxy class");
}
}
this.cl = cl;
this.resolveEx = resolveEx;
this.superDesc = superDesc;
isProxy = true;
serializable = true;
suid = 0L;
fields = NO_FIELDS;
if(osc != null) {
localDesc = osc;
name = localDesc.name;
externalizable = localDesc.externalizable;
writeReplaceMethod = localDesc.writeReplaceMethod;
readResolveMethod = localDesc.readResolveMethod;
deserializeEx = localDesc.deserializeEx;
domains = localDesc.domains;
cons = localDesc.cons;
}
// 返回待序列化的字段的统计信息
fieldRefl = getReflector(fields, localDesc);
initialized = true;
}
/**
* Initializes class descriptor representing a non-proxy class.
*/
// 使用非代理类对象cl来初始化当前序列化描述符
void initNonProxy(ObjectStreamClass model, Class<?> cl, ClassNotFoundException resolveEx, ObjectStreamClass superDesc) throws InvalidClassException {
// 获取待序列化对象的序列化编号
long suid = model.getSerialVersionUID();
ObjectStreamClass osc = null;
if(cl != null) {
// 获取类对象cl的序列化描述符,返回之前会先去缓存中查找
osc = lookup(cl, true);
if(osc.isProxy) {
throw new InvalidClassException("cannot bind non-proxy descriptor to a proxy class");
}
if(model.isEnum != osc.isEnum) {
throw new InvalidClassException(model.isEnum ? "cannot bind enum descriptor to a non-enum class" : "cannot bind non-enum descriptor to an enum class");
}
if(model.serializable == osc.serializable && !cl.isArray() && suid != osc.getSerialVersionUID()) {
throw new InvalidClassException(osc.name, "local class incompatible: " + "stream classdesc serialVersionUID = " + suid + ", local class serialVersionUID = " + osc.getSerialVersionUID());
}
if(!classNamesEqual(model.name, osc.name)) {
throw new InvalidClassException(osc.name, "local class name incompatible with stream class " + "name \"" + model.name + "\"");
}
if(!model.isEnum) {
if((model.serializable == osc.serializable) && (model.externalizable != osc.externalizable)) {
throw new InvalidClassException(osc.name, "Serializable incompatible with Externalizable");
}
if((model.serializable != osc.serializable) || (model.externalizable != osc.externalizable) || !(model.serializable || model.externalizable)) {
deserializeEx = new ExceptionInfo(osc.name, "class invalid for deserialization");
}
}
}
this.cl = cl;
this.resolveEx = resolveEx;
this.superDesc = superDesc;
name = model.name;
this.suid = suid;
isProxy = false;
isEnum = model.isEnum;
serializable = model.serializable;
externalizable = model.externalizable;
hasBlockExternalData = model.hasBlockExternalData;
hasWriteObjectData = model.hasWriteObjectData;
fields = model.fields;
primDataSize = model.primDataSize;
numObjFields = model.numObjFields;
if(osc != null) {
localDesc = osc;
writeObjectMethod = localDesc.writeObjectMethod;
readObjectMethod = localDesc.readObjectMethod;
readObjectNoDataMethod = localDesc.readObjectNoDataMethod;
writeReplaceMethod = localDesc.writeReplaceMethod;
readResolveMethod = localDesc.readResolveMethod;
if(deserializeEx == null) {
deserializeEx = localDesc.deserializeEx;
}
domains = localDesc.domains;
cons = localDesc.cons;
}
// 返回待序列化的字段的统计信息
fieldRefl = getReflector(fields, localDesc);
// reassign to matched fields so as to reflect local unshared settings
fields = fieldRefl.getFields();
initialized = true;
}
/**
* Reads non-proxy class descriptor information from given input stream.
* The resulting class descriptor is not fully functional; it can only be
* used as input to the ObjectInputStream.resolveClass() and
* ObjectStreamClass.initNonProxy() methods.
*/
void readNonProxy(ObjectInputStream in) throws IOException, ClassNotFoundException {
name = in.readUTF();
suid = in.readLong();
isProxy = false;
byte flags = in.readByte();
hasWriteObjectData = ((flags & ObjectStreamConstants.SC_WRITE_METHOD) != 0);
hasBlockExternalData = ((flags & ObjectStreamConstants.SC_BLOCK_DATA) != 0);
externalizable = ((flags & ObjectStreamConstants.SC_EXTERNALIZABLE) != 0);
boolean sflag = ((flags & ObjectStreamConstants.SC_SERIALIZABLE) != 0);
if(externalizable && sflag) {
throw new InvalidClassException(name, "serializable and externalizable flags conflict");
}
serializable = externalizable || sflag;
isEnum = ((flags & ObjectStreamConstants.SC_ENUM) != 0);
if(isEnum && suid.longValue() != 0L) {
throw new InvalidClassException(name, "enum descriptor has non-zero serialVersionUID: " + suid);
}
int numFields = in.readShort();
if(isEnum && numFields != 0) {
throw new InvalidClassException(name, "enum descriptor has non-zero field count: " + numFields);
}
fields = (numFields>0) ? new ObjectStreamField[numFields] : NO_FIELDS;
for(int i = 0; i<numFields; i++) {
char tcode = (char) in.readByte();
String fname = in.readUTF();
String signature = ((tcode == 'L') || (tcode == '[')) ? in.readTypeString() : new String(new char[]{tcode});
try {
fields[i] = new ObjectStreamField(fname, signature, false);
} catch(RuntimeException e) {
throw (IOException) new InvalidClassException(name, "invalid descriptor for field " + fname).initCause(e);
}
}
/*
* 统计fields中原始类型字段所占字节数与引用类型字段的数量,
* 并校验fields中的字段顺序(原始类型排在前面,引用类型排在后面)。
*/
computeFieldOffsets();
}
/**
* Writes non-proxy class descriptor information to given output stream.
*/
// 向输出流out写入当前(非代理对象的)序列化描述符
void writeNonProxy(ObjectOutputStream out) throws IOException {
out.writeUTF(name); // 向最终输出流写入待序列化的类型名称(以UTF8的形式写入)
// 获取待序列化对象的序列化编号
long suid = getSerialVersionUID();
out.writeLong(suid);
byte flags = 0;
if(externalizable) {
flags |= ObjectStreamConstants.SC_EXTERNALIZABLE;
int protocol = out.getProtocolVersion();
if(protocol != ObjectStreamConstants.PROTOCOL_VERSION_1) {
flags |= ObjectStreamConstants.SC_BLOCK_DATA;
}
} else if(serializable) {
flags |= ObjectStreamConstants.SC_SERIALIZABLE;
}
if(hasWriteObjectData) {
flags |= ObjectStreamConstants.SC_WRITE_METHOD;
}
if(isEnum) {
flags |= ObjectStreamConstants.SC_ENUM;
}
out.writeByte(flags);
out.writeShort(fields.length);
for(ObjectStreamField f : fields) {
out.writeByte(f.getTypeCode());
out.writeUTF(f.getName());
if(!f.isPrimitive()) {
out.writeTypeString(f.getTypeString());
}
}
}
/*▲ ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Fetches the serializable primitive field values of object obj and
* marshals them into byte array buf starting at offset 0. It is the
* responsibility of the caller to ensure that obj is of the proper type if
* non-null.
*/
// 返回obj中所有待序列化的基本类型字段的值
void getPrimFieldValues(Object obj, byte[] buf) {
fieldRefl.getPrimFieldValues(obj, buf);
}
/**
* Sets the serializable primitive fields of object obj using values
* unmarshalled from byte array buf starting at offset 0. It is the
* responsibility of the caller to ensure that obj is of the proper type if
* non-null.
*/
void setPrimFieldValues(Object obj, byte[] buf) {
fieldRefl.setPrimFieldValues(obj, buf);
}
/**
* Fetches the serializable object field values of object obj and stores
* them in array vals starting at offset 0. It is the responsibility of
* the caller to ensure that obj is of the proper type if non-null.
*/
// 获取obj中所有待序列化的引用类型字段的值
void getObjFieldValues(Object obj, Object[] vals) {
fieldRefl.getObjFieldValues(obj, vals);
}