forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClassLoader.java
3188 lines (2823 loc) · 142 KB
/
ClassLoader.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) 2013, 2018, 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.lang;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import jdk.internal.loader.BootLoader;
import jdk.internal.loader.BuiltinClassLoader;
import jdk.internal.loader.ClassLoaders;
import jdk.internal.misc.Unsafe;
import jdk.internal.misc.VM;
import jdk.internal.perf.PerfCounter;
import jdk.internal.ref.CleanerFactory;
import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.Reflection;
import sun.reflect.misc.ReflectUtil;
import sun.security.util.SecurityConstants;
/**
* A class loader is an object that is responsible for loading classes. The
* class {@code ClassLoader} is an abstract class. Given the <a
* href="#binary-name">binary name</a> of a class, a class loader should attempt to
* locate or generate data that constitutes a definition for the class. A
* typical strategy is to transform the name into a file name and then read a
* "class file" of that name from a file system.
*
* <p> Every {@link java.lang.Class Class} object contains a {@link
* Class#getClassLoader() reference} to the {@code ClassLoader} that defined
* it.
*
* <p> {@code Class} objects for array classes are not created by class
* loaders, but are created automatically as required by the Java runtime.
* The class loader for an array class, as returned by {@link
* Class#getClassLoader()} is the same as the class loader for its element
* type; if the element type is a primitive type, then the array class has no
* class loader.
*
* <p> Applications implement subclasses of {@code ClassLoader} in order to
* extend the manner in which the Java virtual machine dynamically loads
* classes.
*
* <p> Class loaders may typically be used by security managers to indicate
* security domains.
*
* <p> In addition to loading classes, a class loader is also responsible for
* locating resources. A resource is some data (a "{@code .class}" file,
* configuration data, or an image for example) that is identified with an
* abstract '/'-separated path name. Resources are typically packaged with an
* application or library so that they can be located by code in the
* application or library. In some cases, the resources are included so that
* they can be located by other libraries.
*
* <p> The {@code ClassLoader} class uses a delegation model to search for
* classes and resources. Each instance of {@code ClassLoader} has an
* associated parent class loader. When requested to find a class or
* resource, a {@code ClassLoader} instance will usually delegate the search
* for the class or resource to its parent class loader before attempting to
* find the class or resource itself.
*
* <p> Class loaders that support concurrent loading of classes are known as
* <em>{@linkplain #isRegisteredAsParallelCapable() parallel capable}</em> class
* loaders and are required to register themselves at their class initialization
* time by invoking the {@link
* #registerAsParallelCapable ClassLoader.registerAsParallelCapable}
* method. Note that the {@code ClassLoader} class is registered as parallel
* capable by default. However, its subclasses still need to register themselves
* if they are parallel capable.
* In environments in which the delegation model is not strictly
* hierarchical, class loaders need to be parallel capable, otherwise class
* loading can lead to deadlocks because the loader lock is held for the
* duration of the class loading process (see {@link #loadClass
* loadClass} methods).
*
* <h3> <a id="builtinLoaders">Run-time Built-in Class Loaders</a></h3>
*
* The Java run-time has the following built-in class loaders:
*
* <ul>
* <li><p>Bootstrap class loader.
* It is the virtual machine's built-in class loader, typically represented
* as {@code null}, and does not have a parent.</li>
* <li><p>{@linkplain #getPlatformClassLoader() Platform class loader}.
* All <em>platform classes</em> are visible to the platform class loader
* that can be used as the parent of a {@code ClassLoader} instance.
* Platform classes include Java SE platform APIs, their implementation
* classes and JDK-specific run-time classes that are defined by the
* platform class loader or its ancestors.
* <p> To allow for upgrading/overriding of modules defined to the platform
* class loader, and where upgraded modules read modules defined to class
* loaders other than the platform class loader and its ancestors, then
* the platform class loader may have to delegate to other class loaders,
* the application class loader for example.
* In other words, classes in named modules defined to class loaders
* other than the platform class loader and its ancestors may be visible
* to the platform class loader. </li>
* <li><p>{@linkplain #getSystemClassLoader() System class loader}.
* It is also known as <em>application class loader</em> and is distinct
* from the platform class loader.
* The system class loader is typically used to define classes on the
* application class path, module path, and JDK-specific tools.
* The platform class loader is a parent or an ancestor of the system class
* loader that all platform classes are visible to it.</li>
* </ul>
*
* <p> Normally, the Java virtual machine loads classes from the local file
* system in a platform-dependent manner.
* However, some classes may not originate from a file; they may originate
* from other sources, such as the network, or they could be constructed by an
* application. The method {@link #defineClass(String, byte[], int, int)
* defineClass} converts an array of bytes into an instance of class
* {@code Class}. Instances of this newly defined class can be created using
* {@link Class#newInstance Class.newInstance}.
*
* <p> The methods and constructors of objects created by a class loader may
* reference other classes. To determine the class(es) referred to, the Java
* virtual machine invokes the {@link #loadClass loadClass} method of
* the class loader that originally created the class.
*
* <p> For example, an application could create a network class loader to
* download class files from a server. Sample code might look like:
*
* <blockquote><pre>
* ClassLoader loader = new NetworkClassLoader(host, port);
* Object main = loader.loadClass("Main", true).newInstance();
* . . .
* </pre></blockquote>
*
* <p> The network class loader subclass must define the methods {@link
* #findClass findClass} and {@code loadClassData} to load a class
* from the network. Once it has downloaded the bytes that make up the class,
* it should use the method {@link #defineClass defineClass} to
* create a class instance. A sample implementation is:
*
* <blockquote><pre>
* class NetworkClassLoader extends ClassLoader {
* String host;
* int port;
*
* public Class findClass(String className) {
* byte[] b = loadClassData(className);
* return defineClass(className, b, 0, b.length);
* }
*
* private byte[] loadClassData(String className) {
* // load the class data from the connection
* . . .
* }
* }
* </pre></blockquote>
*
* <h3> <a id="binary-name">Binary names</a> </h3>
*
* <p> Any class name provided as a {@code String} parameter to methods in
* {@code ClassLoader} must be a binary name as defined by
* <cite>The Java™ Language Specification</cite>.
*
* <p> Examples of valid class names include:
* <blockquote><pre>
* "java.lang.String"
* "javax.swing.JSpinner$DefaultEditor"
* "java.security.KeyStore$Builder$FileBuilder$1"
* "java.net.URLClassLoader$3$1"
* </pre></blockquote>
*
* <p> Any package name provided as a {@code String} parameter to methods in
* {@code ClassLoader} must be either the empty string (denoting an unnamed package)
* or a fully qualified name as defined by
* <cite>The Java™ Language Specification</cite>.
*
* @jls 6.7 Fully Qualified Names
* @jls 13.1 The Form of a Binary
* @see #resolveClass(Class)
* @since 1.0
* @revised 9
* @spec JPMS
*/
/*
* 所有类加载器的祖先,主要用于加载类和加载资源
*
* 加载类分为查找类和定义类两个方面
* 开始加载一个类时,先从子级类加载器向上搜索看该类是否已加载过
* 如果该类还未加载,则从父级类加载器向下定义类(将class文件的二进制流转换为JVM类对象)
* 向上搜索类时,只要搜索到目标类,就将结果返回
* 向下定义类时,只要某个类加载器有能力完成加载任务,它就将加载任务揽下来
*/
public abstract class ClassLoader {
/* The system class loader */
// system class loader,可能是内置的AppClassLoader(默认),也可能是自定义的类加载器
private static volatile ClassLoader scl;
/**
* The parent class loader for delegation
* Note: VM hardcoded the offset of this field, thus all new fields must be added *after* it.
*/
// 父级类加载器,需要与BuiltinClassLoader中的parent区分
private final ClassLoader parent;
/** class loader name */
// 当前ClassLoader的名称
private final String name;
/** the unnamed module for this ClassLoader */
// 当前ClassLoader定义的未命名模块
private final Module unnamedModule;
/** a string for exception message printing */
// 名称与ID
private final String nameAndId;
/**
* Maps class name to the corresponding lock object when the current class loader is parallel capable.
* Note: VM also uses this field to decide if the current class loader is parallel capable and the appropriate lock object for class loading.
*/
// 当前类加载器具有并行功能时,将其下的类名映射到锁对象
private final ConcurrentHashMap<String, Object> parallelLockMap;
// 将包名映射到身份证书
private final Map <String, Certificate[]> package2certs;
/**
* The classes loaded by this class loader.
* The only purpose of this table is to keep the classes from being GC'ed until the loader is GC'ed.
*/
// 记录当前类加载器加载的类
private final Vector<Class<?>> classes = new Vector<>();
/**
* The packages defined in this class loader.
* Each package name is mapped to its corresponding NamedPackage object.
* The value is a Package object if
* ClassLoader::definePackage, Class::getPackage, ClassLoader::getDefinePackage(s) or Package::getPackage(s) method is called to define it.
* Otherwise, the value is a NamedPackage object.
*/
// 记录当前类加载器定义的包
private final ConcurrentHashMap<String, NamedPackage> packages = new ConcurrentHashMap<>();
// The "default" domain. Set as the default ProtectionDomain on newly created classes.
private final ProtectionDomain defaultDomain = new ProtectionDomain(new CodeSource(null, (Certificate[]) null), null, this, null);
// Shared among all packages with unsigned classes
private static final Certificate[] nocerts = new Certificate[0];
private static native void registerNatives();
static {
registerNatives();
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates a new class loader using the {@code ClassLoader} returned by
* the method {@link #getSystemClassLoader()
* getSystemClassLoader()} as the parent class loader.
*
* <p> If there is a security manager, its {@link
* SecurityManager#checkCreateClassLoader()
* checkCreateClassLoader} method is invoked. This may result in
* a security exception. </p>
*
* @throws SecurityException If a security manager exists and its
* {@code checkCreateClassLoader} method doesn't allow creation
* of a new class loader.
*/
protected ClassLoader() {
this(checkCreateClassLoader(), null, getSystemClassLoader());
}
/**
* Creates a new class loader using the specified parent class loader for
* delegation.
*
* <p> If there is a security manager, its {@link
* SecurityManager#checkCreateClassLoader() checkCreateClassLoader} method
* is invoked. This may result in a security exception. </p>
*
* @param parent The parent class loader
*
* @throws SecurityException If a security manager exists and its
* {@code checkCreateClassLoader} method doesn't allow creation
* of a new class loader.
* @apiNote If the parent is specified as {@code null} (for the
* bootstrap class loader) then there is no guarantee that all platform
* classes are visible.
* @since 1.2
*/
protected ClassLoader(ClassLoader parent) {
this(checkCreateClassLoader(), null, parent);
}
/**
* Creates a new class loader of the specified name and using the
* specified parent class loader for delegation.
*
* @param name class loader name; or {@code null} if not named
* @param parent the parent class loader
*
* @throws IllegalArgumentException if the given name is empty.
* @throws SecurityException If a security manager exists and its
* {@link SecurityManager#checkCreateClassLoader()}
* method doesn't allow creation of a new class loader.
* @apiNote If the parent is specified as {@code null} (for the
* bootstrap class loader) then there is no guarantee that all platform
* classes are visible.
* @spec JPMS
* @since 9
*/
protected ClassLoader(String name, ClassLoader parent) {
this(checkCreateClassLoader(name), name, parent);
}
private ClassLoader(Void unused, String name, ClassLoader parent) {
this.name = name;
this.parent = parent;
this.unnamedModule = new Module(this);
if(ParallelLoaders.isRegistered(this.getClass())) {
parallelLockMap = new ConcurrentHashMap<>();
package2certs = new ConcurrentHashMap<>();
assertionLock = new Object();
} else {
// no finer-grained lock; lock on the classloader instance
parallelLockMap = null;
package2certs = new Hashtable<>();
assertionLock = this;
}
// 返回当前ClassLoader的名称和一串随机id
this.nameAndId = nameAndId(this);
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 加载类 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Loads the class with the specified <a href="#binary-name">binary name</a>.
* This method searches for classes in the same manner as the {@link
* #loadClass(String, boolean)} method. It is invoked by the Java virtual
* machine to resolve class references. Invoking this method is equivalent
* to invoking {@link #loadClass(String, boolean) loadClass(name,
* false)}.
*
* @param className The <a href="#binary-name">binary name</a> of the class
*
* @return The resulting {@code Class} object
*
* @throws ClassNotFoundException If the class was not found
*/
// 根据给定类的全名加载类
public Class<?> loadClass(String className) throws ClassNotFoundException {
return loadClass(className, false);
}
/**
* Loads the class with the specified <a href="#binary-name">binary name</a>.
* The default implementation of this method searches for classes in the following order:
*
* <ol>
*
* <li><p> Invoke {@link #findLoadedClass(String)} to check if the class
* has already been loaded. </p></li>
*
* <li><p> Invoke the {@link #loadClass(String) loadClass} method
* on the parent class loader. If the parent is {@code null} the class
* loader built into the virtual machine is used, instead. </p></li>
*
* <li><p> Invoke the {@link #findClass(String)} method to find the
* class. </p></li>
*
* </ol>
*
* <p> If the class was found using the above steps, and the
* {@code resolve} flag is true, this method will then invoke the {@link
* #resolveClass(Class)} method on the resulting {@code Class} object.
*
* <p> Subclasses of {@code ClassLoader} are encouraged to override {@link
* #findClass(String)}, rather than this method. </p>
*
* <p> Unless overridden, this method synchronizes on the result of
* {@link #getClassLoadingLock getClassLoadingLock} method
* during the entire class loading process.
*
* @param className The <a href="#binary-name">binary name</a> of the class
* @param resolve If {@code true} then resolve the class
*
* @return The resulting {@code Class} object
*
* @throws ClassNotFoundException If the class could not be found
*/
// 根据给定类的全名加载类,resolve指示是否链接类
protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {
synchronized(getClassLoadingLock(className)) {
// 查找指定的类,如果该类未被当前类加载器加载,返回null
Class<?> c = findLoadedClass(className);
// 如果该类还未加载
if(c == null) {
long t0 = System.nanoTime();
// 根据双亲委托机制,先使用父级类加载器加载指定的类
try {
if(parent != null) {
c = parent.loadClass(className, false);
} else {
// 查找指定的类,如果该类未被bootstrap类加载器加载,返回null
c = findBootstrapClassOrNull(className);
}
} catch(ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found from the non-null parent class loader
}
// 经过查询,发现该类还没被加载
if(c == null) {
// If still not found, then invoke findClass in order to find the class.
long t1 = System.nanoTime();
// 查找(定义)类,如果该类在模块中,则在模块中查找该类,否则在类路径下查找(如果待查找的类存在,则会加载器字节码,并交给虚拟机去定义)
c = findClass(name);
// this is the defining class loader; record the stats
PerfCounter.getParentDelegationTime().addTime(t1 - t0);
PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
PerfCounter.getFindClasses().increment();
}
}
if(resolve) {
resolveClass(c);
}
return c;
}
}
/**
* Loads the class with the specified <a href="#binary-name">binary name</a>
* in a module defined to this class loader. This method returns {@code null}
* if the class could not be found.
*
* @param module The module
* @param className The <a href="#binary-name">binary name</a> of the class
*
* @return The resulting {@code Class} object in a module defined by
* this class loader, or {@code null} if the class could not be found.
*
* @apiNote This method does not delegate to the parent class loader.
* @implSpec The default implementation of this method searches for classes
* in the following order:
*
* <ol>
* <li>Invoke {@link #findLoadedClass(String)} to check if the class
* has already been loaded.</li>
* <li>Invoke the {@link #findClass(String, String)} method to find the
* class in the given module.</li>
* </ol>
*/
// 根据给定的模块名与类的全名加载类
final Class<?> loadClass(Module module, String className) {
synchronized(getClassLoadingLock(className)) {
// 首先检查该类是否已经加载
Class<?> c = findLoadedClass(className);
if(c == null) {
// 查找(定义)类,如果moduleName不为空,则在指定模块中查找该类,否则在类路径下查找(如果待查找的类存在,则会加载器字节码,并交给虚拟机去定义)
c = findClass(module.getName(), className);
}
if(c != null && c.getModule() == module) {
return c;
} else {
return null;
}
}
}
/**
* Finds a class with the specified <a href="#binary-name">binary name</a>,
* loading it if necessary.
*
* <p> This method loads the class through the system class loader (see
* {@link #getSystemClassLoader()}). The {@code Class} object returned
* might have more than one {@code ClassLoader} associated with it.
* Subclasses of {@code ClassLoader} need not usually invoke this method,
* because most class loaders need to override just {@link
* #findClass(String)}. </p>
*
* @param className The <a href="#binary-name">binary name</a> of the class
*
* @return The {@code Class} object for the specified {@code name}
*
* @throws ClassNotFoundException If the class could not be found
* @see #ClassLoader(ClassLoader)
* @see #getParent()
*/
// 使用system类加载器加载指定的类
protected final Class<?> findSystemClass(String className) throws ClassNotFoundException {
return getSystemClassLoader().loadClass(className);
}
/*▲ 加载类 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 查找(定义)类 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Finds the class with the specified <a href="#binary-name">binary name</a>.
* This method should be overridden by class loader implementations that
* follow the delegation model for loading classes, and will be invoked by
* the {@link #loadClass loadClass} method after checking the
* parent class loader for the requested class.
*
* @param className The <a href="#binary-name">binary name</a> of the class
*
* @return The resulting {@code Class} object
*
* @throws ClassNotFoundException If the class could not be found
* @implSpec The default implementation throws {@code ClassNotFoundException}.
* @since 1.2
*/
// [子类覆盖]查找(定义)类,如果该类在模块中,则在模块中查找该类,否则在类路径下查找(如果待查找的类存在,则会加载器字节码,并交给虚拟机去定义)
protected Class<?> findClass(String className) throws ClassNotFoundException {
throw new ClassNotFoundException(className);
}
/**
* Finds the class with the given <a href="#binary-name">binary name</a>
* in a module defined to this class loader.
* Class loader implementations that support loading from modules
* should override this method.
*
* @param moduleName The module name; or {@code null} to find the class in the
* {@linkplain #getUnnamedModule() unnamed module} for this
* class loader
* @param className The <a href="#binary-name">binary name</a> of the class
*
* @return The resulting {@code Class} object, or {@code null}
* if the class could not be found.
*
* @apiNote This method returns {@code null} rather than throwing
* {@code ClassNotFoundException} if the class could not be found.
* @implSpec The default implementation attempts to find the class by
* invoking {@link #findClass(String)} when the {@code moduleName} is
* {@code null}. It otherwise returns {@code null}.
* @spec JPMS
* @since 9
*/
// [子类覆盖]查找(定义)类,如果moduleName不为空,则在指定模块中查找该类,否则在类路径下查找(如果待查找的类存在,则会加载器字节码,并交给虚拟机去定义)
protected Class<?> findClass(String moduleName, String className) {
if(moduleName == null) {
try {
return findClass(className);
} catch(ClassNotFoundException ignore) {
}
}
return null;
}
/*▲ 查找(定义)类 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 定义类 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Converts a {@link java.nio.ByteBuffer ByteBuffer} into an instance
* of class {@code Class}, with the given {@code ProtectionDomain}.
* If the given {@code ProtectionDomain} is {@code null}, then a default
* protection domain will be assigned to the class as
* specified in the documentation for {@link #defineClass(String, byte[],
* int, int)}. Before the class can be used it must be resolved.
*
* <p>The rules about the first class defined in a package determining the
* set of certificates for the package, the restrictions on class names,
* and the defined package of the class
* are identical to those specified in the documentation for {@link
* #defineClass(String, byte[], int, int, ProtectionDomain)}.
*
* <p> An invocation of this method of the form
* <i>cl</i>{@code .defineClass(}<i>name</i>{@code ,}
* <i>bBuffer</i>{@code ,} <i>pd</i>{@code )} yields exactly the same
* result as the statements
*
* <p> <code>
* ...<br>
* byte[] temp = new byte[bBuffer.{@link
* java.nio.ByteBuffer#remaining remaining}()];<br>
* bBuffer.{@link java.nio.ByteBuffer#get(byte[])
* get}(temp);<br>
* return {@link #defineClass(String, byte[], int, int, ProtectionDomain)
* cl.defineClass}(name, temp, 0,
* temp.length, pd);<br>
* </code></p>
*
* @param className The expected <a href="#binary-name">binary name</a>. of the class, or
* {@code null} if not known
* @param b The bytes that make up the class data. The bytes from positions
* {@code b.position()} through {@code b.position() + b.limit() -1
* } should have the format of a valid class file as defined by
* <cite>The Java™ Virtual Machine Specification</cite>.
* @param protectionDomain The {@code ProtectionDomain} of the class, or {@code null}.
*
* @return The {@code Class} object created from the data,
* and {@code ProtectionDomain}.
*
* @throws ClassFormatError If the data did not contain a valid class.
* @throws NoClassDefFoundError If {@code name} is not {@code null} and not equal to the
* <a href="#binary-name">binary name</a> of the class specified by {@code b}
* @throws SecurityException If an attempt is made to add this class to a package that
* contains classes that were signed by a different set of
* certificates than this class, or if {@code name} begins with
* "{@code java.}".
* @revised 9
* @spec JPMS
* @see #defineClass(String, byte[], int, int, ProtectionDomain)
* @since 1.5
*/
// 利用存储在缓冲区中的字节码去定义类
protected final Class<?> defineClass(String className, ByteBuffer b, ProtectionDomain protectionDomain) throws ClassFormatError {
// 获取二进制流长度
int len = b.remaining();
// 如果不是直接缓冲区,则使用byte[]存储该二进制流
if(!b.isDirect()) {
if(b.hasArray()) {
return defineClass(className, b.array(), b.position() + b.arrayOffset(), len, protectionDomain);
} else {
// no array, or read-only array
byte[] tb = new byte[len];
b.get(tb); // get bytes out of byte buffer.
return defineClass(className, tb, 0, len, protectionDomain);
}
}
protectionDomain = preDefineClass(className, protectionDomain);
// 从保护域中获取代码源的位置信息
String source = defineClassSourceLocation(protectionDomain);
Class<?> clazz = defineClass2(this, className, b, b.position(), len, protectionDomain, source);
postDefineClass(clazz, protectionDomain);
return clazz;
}
/**
* Converts an array of bytes into an instance of class {@code Class},
* with a given {@code ProtectionDomain}.
*
* <p> If the given {@code ProtectionDomain} is {@code null},
* then a default protection domain will be assigned to the class as specified
* in the documentation for {@link #defineClass(String, byte[], int, int)}.
* Before the class can be used it must be resolved.
*
* <p> The first class defined in a package determines the exact set of
* certificates that all subsequent classes defined in that package must
* contain. The set of certificates for a class is obtained from the
* {@link java.security.CodeSource CodeSource} within the
* {@code ProtectionDomain} of the class. Any classes added to that
* package must contain the same set of certificates or a
* {@code SecurityException} will be thrown. Note that if
* {@code name} is {@code null}, this check is not performed.
* You should always pass in the <a href="#binary-name">binary name</a> of the
* class you are defining as well as the bytes. This ensures that the
* class you are defining is indeed the class you think it is.
*
* <p> If the specified {@code name} begins with "{@code java.}", it can
* only be defined by the {@linkplain #getPlatformClassLoader()
* platform class loader} or its ancestors; otherwise {@code SecurityException}
* will be thrown. If {@code name} is not {@code null}, it must be equal to
* the <a href="#binary-name">binary name</a> of the class
* specified by the byte array {@code b}, otherwise a {@link
* NoClassDefFoundError NoClassDefFoundError} will be thrown.
*
* <p> This method defines a package in this class loader corresponding to the
* package of the {@code Class} (if such a package has not already been defined
* in this class loader). The name of the defined package is derived from
* the <a href="#binary-name">binary name</a> of the class specified by
* the byte array {@code b}.
* Other properties of the defined package are as specified by {@link Package}.
*
* @param className The expected <a href="#binary-name">binary name</a> of the class, or
* {@code null} if not known
* @param b The bytes that make up the class data. The bytes in positions
* {@code off} through {@code off+len-1} should have the format
* of a valid class file as defined by
* <cite>The Java™ Virtual Machine Specification</cite>.
* @param off The start offset in {@code b} of the class data
* @param len The length of the class data
* @param protectionDomain The {@code ProtectionDomain} of the class
*
* @return The {@code Class} object created from the data,
* and {@code ProtectionDomain}.
*
* @throws ClassFormatError If the data did not contain a valid class
* @throws NoClassDefFoundError If {@code name} is not {@code null} and not equal to the
* <a href="#binary-name">binary name</a> of the class specified by {@code b}
* @throws IndexOutOfBoundsException If either {@code off} or {@code len} is negative, or if
* {@code off+len} is greater than {@code b.length}.
* @throws SecurityException If an attempt is made to add this class to a package that
* contains classes that were signed by a different set of
* certificates than this class, or if {@code name} begins with
* "{@code java.}" and this class loader is not the platform
* class loader or its ancestor.
* @revised 9
* @spec JPMS
*/
// 利用存储在字节数组中的字节码去定义类
protected final Class<?> defineClass(String className, byte[] b, int off, int len, ProtectionDomain protectionDomain) throws ClassFormatError {
// 预定义类,主要是进行一些安全检查和证书设置
protectionDomain = preDefineClass(className, protectionDomain);
// 从保护域中获取代码源的位置信息
String source = defineClassSourceLocation(protectionDomain);
// 由虚拟机调用,用来定义类(将class字节码加载到JVM)
Class<?> clazz = defineClass1(this, className, b, off, len, protectionDomain, source);
// 在类定义完之后的一些收尾操作,主要是定义NamedPackage和设置签名
postDefineClass(clazz, protectionDomain);
return clazz;
}
/**
* Converts an array of bytes into an instance of class {@code Class}.
* Before the {@code Class} can be used it must be resolved.
*
* <p> This method assigns a default {@link java.security.ProtectionDomain
* ProtectionDomain} to the newly defined class. The
* {@code ProtectionDomain} is effectively granted the same set of
* permissions returned when {@link
* java.security.Policy#getPermissions(java.security.CodeSource)
* Policy.getPolicy().getPermissions(new CodeSource(null, null))}
* is invoked. The default protection domain is created on the first invocation
* of {@link #defineClass(String, byte[], int, int) defineClass},
* and re-used on subsequent invocations.
*
* <p> To assign a specific {@code ProtectionDomain} to the class, use
* the {@link #defineClass(String, byte[], int, int,
* java.security.ProtectionDomain) defineClass} method that takes a
* {@code ProtectionDomain} as one of its arguments. </p>
*
* <p>
* This method defines a package in this class loader corresponding to the
* package of the {@code Class} (if such a package has not already been defined
* in this class loader). The name of the defined package is derived from
* the <a href="#binary-name">binary name</a> of the class specified by
* the byte array {@code b}.
* Other properties of the defined package are as specified by {@link Package}.
*
* @param className The expected <a href="#binary-name">binary name</a> of the class, or
* {@code null} if not known
* @param b The bytes that make up the class data. The bytes in positions
* {@code off} through {@code off+len-1} should have the format
* of a valid class file as defined by
* <cite>The Java™ Virtual Machine Specification</cite>.
* @param off The start offset in {@code b} of the class data
* @param len The length of the class data
*
* @return The {@code Class} object that was created from the specified
* class data.
*
* @throws ClassFormatError If the data did not contain a valid class
* @throws IndexOutOfBoundsException If either {@code off} or {@code len} is negative, or if
* {@code off+len} is greater than {@code b.length}.
* @throws SecurityException If an attempt is made to add this class to a package that
* contains classes that were signed by a different set of
* certificates than this class (which is unsigned), or if
* {@code name} begins with "{@code java.}".
* @revised 9
* @spec JPMS
* @see #loadClass(String, boolean)
* @see #resolveClass(Class)
* @see java.security.CodeSource
* @see java.security.SecureClassLoader
* @since 1.1
*/
// 利用存储在字节数组中的字节码去定义类(无保护域)
protected final Class<?> defineClass(String className, byte[] b, int off, int len) throws ClassFormatError {
return defineClass(className, b, off, len, null);
}
/**
* Converts an array of bytes into an instance of class {@code Class}.
* Before the {@code Class} can be used it must be resolved. This method
* is deprecated in favor of the version that takes a <a
* href="#binary-name">binary name</a> as its first argument, and is more secure.
*
* @param b The bytes that make up the class data. The bytes in positions
* {@code off} through {@code off+len-1} should have the format
* of a valid class file as defined by
* <cite>The Java™ Virtual Machine Specification</cite>.
* @param off The start offset in {@code b} of the class data
* @param len The length of the class data
*
* @return The {@code Class} object that was created from the specified
* class data
*
* @throws ClassFormatError If the data did not contain a valid class
* @throws IndexOutOfBoundsException If either {@code off} or {@code len} is negative, or if
* {@code off+len} is greater than {@code b.length}.
* @throws SecurityException If an attempt is made to add this class to a package that
* contains classes that were signed by a different set of
* certificates than this class, or if an attempt is made
* to define a class in a package with a fully-qualified name
* that starts with "{@code java.}".
* @see #loadClass(String, boolean)
* @see #resolveClass(Class)
* @deprecated Replaced by {@link #defineClass(String, byte[], int, int) defineClass(String, byte[], int, int)}
*/
// 利用存储在字节数组中的字节码去定义类(无保护域)
@Deprecated(since = "1.1")
protected final Class<?> defineClass(byte[] b, int off, int len) throws ClassFormatError {
return defineClass(null, b, off, len, null);
}
static native Class<?> defineClass1(ClassLoader loader, String className, byte[] b, int off, int len, ProtectionDomain pd, String source);
static native Class<?> defineClass2(ClassLoader loader, String className, ByteBuffer b, int off, int len, ProtectionDomain pd, String source);
/*▲ 定义类 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 链接类 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Links the specified class.
*
* This (misleadingly named) method may be used by a class loader to link a class.
* If the class {@code c} has already been linked, then this method simply returns.
* Otherwise, the class is linked as described in the "Execution" chapter of <cite>The Java™ Language Specification</cite>.
*
* @param clazz The class to link
*
* @throws NullPointerException If {@code c} is {@code null}.
* @see #defineClass(String, byte[], int, int)
*/
// 链接类
protected final void resolveClass(Class<?> clazz) {
if(clazz == null) {
throw new NullPointerException();
}
}
/*▲ 链接类 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 查找类 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the class with the given <a href="#binary-name">binary name</a> if this
* loader has been recorded by the Java virtual machine as an initiating
* loader of a class with that <a href="#binary-name">binary name</a>. Otherwise
* {@code null} is returned.
*
* @param className The <a href="#binary-name">binary name</a> of the class
*
* @return The {@code Class} object, or {@code null} if the class has
* not been loaded
*
* @since 1.1
*/
// 查找指定的类,如果该类未被当前类加载器加载,返回null
protected final Class<?> findLoadedClass(String className) {
if(!checkName(className)) {
return null;
}
return findLoadedClass0(className);
}
/**
* Returns a class loaded by the bootstrap class loader; or return null if not found.
*/
// 查找指定的类,如果该类未被bootstrap类加载器加载,返回null
Class<?> findBootstrapClassOrNull(String className) {
if(!checkName(className)) {
return null;
}
return findBootstrapClass(className);
}
// 查找指定的类,如果该类未被当前类加载器加载,返回null
private final native Class<?> findLoadedClass0(String className);
// 查找指定的类,如果该类未被bootstrap类加载器加载,返回null
private native Class<?> findBootstrapClass(String className);
/*▲ 查找类 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 查找资源(局部) ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Finds the resource with the given name. Class loader implementations
* should override this method.
*
* <p> For resources in named modules then the method must implement the
* rules for encapsulation specified in the {@code Module} {@link
* Module#getResourceAsStream getResourceAsStream} method. Additionally,
* it must not find non-"{@code .class}" resources in packages of named
* modules unless the package is {@link Module#isOpen(String) opened}
* unconditionally. </p>
*
* @param resName The resource name
*
* @return {@code URL} object for reading the resource; {@code null} if
* the resource could not be found, a {@code URL} could not be
* constructed to locate the resource, the resource is in a package
* that is not opened unconditionally, or access to the resource is
* denied by the security manager.
*
* @implSpec The default implementation returns {@code null}.
* @revised 9
* @spec JPMS
* @since 1.2
*/
// [子类覆盖]在当前类加载器可以访问到的模块路径/类路径下搜索首个匹配的资源
protected URL findResource(String resName) {
return null;
}
/**
* Returns a URL to a resource in a module defined to this class loader.
* Class loader implementations that support loading from modules
* should override this method.
*
* @param moduleName The module name; or {@code null} to find a resource in the
* {@linkplain #getUnnamedModule() unnamed module} for this