-
Notifications
You must be signed in to change notification settings - Fork 668
/
Module.java
1903 lines (1637 loc) · 74.9 KB
/
Module.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) 2014, 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.lang;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.module.Configuration;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.Exports;
import java.lang.module.ModuleDescriptor.Opens;
import java.lang.module.ModuleDescriptor.Version;
import java.lang.module.ModuleReference;
import java.lang.module.ResolvedModule;
import java.lang.reflect.AnnotatedElement;
import java.net.URI;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jdk.internal.loader.BootLoader;
import jdk.internal.loader.BuiltinClassLoader;
import jdk.internal.loader.ClassLoaders;
import jdk.internal.misc.VM;
import jdk.internal.module.IllegalAccessLogger;
import jdk.internal.module.ModuleLoaderMap;
import jdk.internal.module.Resources;
import jdk.internal.module.ServicesCatalog;
import jdk.internal.org.objectweb.asm.AnnotationVisitor;
import jdk.internal.org.objectweb.asm.Attribute;
import jdk.internal.org.objectweb.asm.ClassReader;
import jdk.internal.org.objectweb.asm.ClassVisitor;
import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.ModuleVisitor;
import jdk.internal.org.objectweb.asm.Opcodes;
import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.Reflection;
import sun.security.util.SecurityConstants;
/**
* Represents a run-time module, either {@link #isNamed() named} or unnamed.
*
* <p> Named modules have a {@link #getName() name} and are constructed by the
* Java Virtual Machine when a graph of modules is defined to the Java virtual
* machine to create a {@linkplain ModuleLayer module layer}. </p>
*
* <p> An unnamed module does not have a name. There is an unnamed module for
* each {@link ClassLoader ClassLoader}, obtained by invoking its {@link
* ClassLoader#getUnnamedModule() getUnnamedModule} method. All types that are
* not in a named module are members of their defining class loader's unnamed
* module. </p>
*
* <p> The package names that are parameters or returned by methods defined in
* this class are the fully-qualified names of the packages as defined in
* section 6.5.3 of <cite>The Java™ Language Specification</cite>, for
* example, {@code "java.lang"}. </p>
*
* <p> Unless otherwise specified, passing a {@code null} argument to a method
* in this class causes a {@link NullPointerException NullPointerException} to
* be thrown. </p>
*
* @since 9
* @spec JPMS
* @see Class#getModule()
*/
// 反射元素-模块(表示一个运行时模块)
public final class Module implements AnnotatedElement {
/** the module descriptor */
// 当前模块的模块描述符(module-info)
private final ModuleDescriptor descriptor;
/** the layer that contains this module, can be null */
// 当前模块所处的模块层
private final ModuleLayer layer;
/** module name and loader, these fields are read by VM */
// 模块名称,对于未命名模块,name为null
private final String name;
// 加载该模块的类加载器
private final ClassLoader loader;
/** the modules that this module reads */
// (运行时)记录当前模块依赖(requires)哪些模块
private volatile Set<Module> reads;
/** the packages that are exported, can be null if the value contains EVERYONE_MODULE then the package is exported to all */
/*
* (运行时)记录当前模块将哪些包导出(exports)给了哪些模块
*
* 注:opens行为会覆盖exports行为,即开放(open)会包含导出(exports);
* 换句话说,isOpen()成立,则isExported()也成立。
*/
private volatile Map<String, Set<Module>> exportedPackages;
/** the packages are open to other modules, can be null if the value contains EVERYONE_MODULE then the package is open to all */
/*
* (运行时)记录当前模块将哪些包开放(open)给了哪些模块
*
* 注:opens行为会覆盖exports行为,即开放(open)会包含导出(exports);
* 换句话说,isOpen()成立,则isExported()也成立。
*/
private volatile Map<String, Set<Module>> openPackages;
/** special Module to mean "all unnamed modules" */
private static final Module ALL_UNNAMED_MODULE = new Module(null);
private static final Set<Module> ALL_UNNAMED_MODULE_SET = Set.of(ALL_UNNAMED_MODULE);
/** special Module to mean "everyone" */
private static final Module EVERYONE_MODULE = new Module(null);
private static final Set<Module> EVERYONE_SET = Set.of(EVERYONE_MODULE);
// cached class file with annotations
private volatile Class<?> moduleInfoClass; // module-info.class
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates a new named Module.
* The resulting Module will be defined to the VM but will not read any other modules,
* will not have any exports setup and will not be registered in the service catalog.
*/
// 构造模块一个命名模块,会通知虚拟机
Module(ModuleLayer layer, ClassLoader loader, ModuleDescriptor descriptor, URI uri) {
this.layer = layer;
this.name = descriptor.name();
this.loader = loader;
this.descriptor = descriptor;
/* define module to VM */
boolean isOpen = descriptor.isOpen() || descriptor.isAutomatic();
Version version = descriptor.version().orElse(null);
String vs = Objects.toString(version, null);
String loc = Objects.toString(uri, null);
String[] packages = descriptor.packages().toArray(new String[0]);
defineModule0(this, isOpen, vs, loc, packages);
}
/**
* Create the unnamed Module for the given ClassLoader.
*
* @see ClassLoader#getUnnamedModule
*/
Module(ClassLoader loader) {
this.layer = null;
this.name = null;
this.loader = loader;
this.descriptor = null;
}
/**
* Creates a named module but without defining the module to the VM.
*
* @apiNote This constructor is for VM white-box testing.
*/
// 创建一个命名模块,由虚拟机调用
Module(ClassLoader loader, ModuleDescriptor descriptor) {
this.layer = null;
this.name = descriptor.name();
this.loader = loader;
this.descriptor = descriptor;
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 关联信息 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns {@code true} if this module is a named module.
*
* @return {@code true} if this is a named module
*
* @see ClassLoader#getUnnamedModule()
*/
// 该模块是否有名称(是否为命名模块)
public boolean isNamed() {
return name != null;
}
/**
* Returns the module name or {@code null} if this module is an unnamed
* module.
*
* @return The module name
*/
// 获取模块名称
public String getName() {
return name;
}
/**
* Returns the {@code ClassLoader} for this module.
*
* <p> If there is a security manager then its {@code checkPermission}
* method if first called with a {@code RuntimePermission("getClassLoader")}
* permission to check that the caller is allowed to get access to the
* class loader. </p>
*
* @return The class loader for this module
*
* @throws SecurityException If denied by the security manager
*/
// 获取加载该模块的类加载器
public ClassLoader getClassLoader() {
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
return loader;
}
/**
* Returns the module descriptor for this module or {@code null} if this
* module is an unnamed module.
*
* @return The module descriptor for this module
*/
// 获取该模块的模块描述符
public ModuleDescriptor getDescriptor() {
return descriptor;
}
/**
* Returns the module layer that contains this module or {@code null} if
* this module is not in a module layer.
*
* A module layer contains named modules and therefore this method always
* returns {@code null} when invoked on an unnamed module.
*
* <p> <a href="reflect/Proxy.html#dynamicmodule">Dynamic modules</a> are
* named modules that are generated at runtime. A dynamic module may or may
* not be in a module layer. </p>
*
* @return The module layer that contains this module
*
* @see java.lang.reflect.Proxy
*/
// 获取该模块所在的模块层;如果是未命名模块,则返回null
public ModuleLayer getLayer() {
if(!isNamed()) {
return null; // 未命名模块不在模块层中
}
ModuleLayer layer = this.layer;
if(layer != null) {
return layer;
}
// special-case java.base as it is created before the boot layer
if(loader == null && name.equals("java.base")) {
return ModuleLayer.boot();
}
return null;
}
/**
* Returns the set of package names for the packages in this module.
*
* <p> For named modules, the returned set contains an element for each
* package in the module. </p>
*
* <p> For unnamed modules, this method is the equivalent to invoking the
* {@link ClassLoader#getDefinedPackages() getDefinedPackages} method of
* this module's class loader and returning the set of package names. </p>
*
* @return the set of the package names of the packages in this module
*/
// 获取当前模块下辖的包
public Set<String> getPackages() {
if (isNamed()) {
return descriptor.packages();
} else {
// unnamed module
Stream<Package> packages;
if (loader == null) {
packages = BootLoader.packages();
} else {
packages = loader.packages();
}
return packages.map(Package::getName).collect(Collectors.toSet());
}
}
/**
* Returns an input stream for reading a resource in this module.
* The {@code name} parameter is a {@code '/'}-separated path name that
* identifies the resource. As with {@link Class#getResourceAsStream
* Class.getResourceAsStream}, this method delegates to the module's class
* loader {@link ClassLoader#findResource(String, String)
* findResource(String,String)} method, invoking it with the module name
* (or {@code null} when the module is unnamed) and the name of the
* resource. If the resource name has a leading slash then it is dropped
* before delegation.
*
* <p> A resource in a named module may be <em>encapsulated</em> so that
* it cannot be located by code in other modules. Whether a resource can be
* located or not is determined as follows: </p>
*
* <ul>
* <li> If the resource name ends with "{@code .class}" then it is not
* encapsulated. </li>
*
* <li> A <em>package name</em> is derived from the resource name. If
* the package name is a {@linkplain #getPackages() package} in the
* module then the resource can only be located by the caller of this
* method when the package is {@linkplain #isOpen(String, Module) open}
* to at least the caller's module. If the resource is not in a
* package in the module then the resource is not encapsulated. </li>
* </ul>
*
* <p> In the above, the <em>package name</em> for a resource is derived
* from the subsequence of characters that precedes the last {@code '/'} in
* the name and then replacing each {@code '/'} character in the subsequence
* with {@code '.'}. A leading slash is ignored when deriving the package
* name. As an example, the package name derived for a resource named
* "{@code a/b/c/foo.properties}" is "{@code a.b.c}". A resource name
* with the name "{@code META-INF/MANIFEST.MF}" is never encapsulated
* because "{@code META-INF}" is not a legal package name. </p>
*
* <p> This method returns {@code null} if the resource is not in this
* module, the resource is encapsulated and cannot be located by the caller,
* or access to the resource is denied by the security manager. </p>
*
* @param name The resource name
*
* @return An input stream for reading the resource or {@code null}
*
* @throws IOException If an I/O error occurs
* @see Class#getResourceAsStream(String)
*/
/*
* 在当前模块路径(根目录)或加载当前模块的类加载器关联的类路径(根目录)下查找名称为resName的资源;如果成功找到资源,则返回其入流
*
* 注:resName前的"/"将被忽略
*/
@CallerSensitive
public InputStream getResourceAsStream(String resName) throws IOException {
if(resName.startsWith("/")) {
resName = resName.substring(1);
}
// 该模块为命名模块,且指定名称的资源可以被封装(resName不以"/"或".class"结尾)
if(isNamed() && Resources.canEncapsulate(resName)) {
// 获取getResourceAsStream()方法的调用者所处的类
Class<?> callerClass = Reflection.getCallerClass();
// 获取callerClass所在模块
Module callerModule = getCallerModule(callerClass);
// 调用者不是当前模块,也不是java.base模块(比如模块B的对象在模块A中的类上加载资源)
if(callerModule != this && callerModule != Object.class.getModule()) {
// 获取指定名称的资源所在的包
String pn = Resources.toPackageName(resName);
// 如果资源所在的包隶属于当前模块下,则需要判断callerModule对pn包是否有访问权限
if(getPackages().contains(pn)) {
// 如果调用者为null,且当前模块的pn包未open
if(callerModule == null && !isOpen(pn)) {
// no caller, package not open
return null;
}
// 如果调用者存在,且当前模块没有将pn包open给other模块callerModule
if(!isOpen(pn, callerModule)) {
// package not open to caller
return null;
}
}
}
}
// 获取当前模块的名称
String mn = this.name;
/* special-case built-in class loaders to avoid URL connection */
if(loader == null) {
// 在指定的模块路径(根目录)或bootstrap类加载器关联的类路径(根目录)下查找匹配的资源;如果成功找到资源,则返回其入流
return BootLoader.findResourceAsStream(mn, resName);
} else if(loader instanceof BuiltinClassLoader) {
// 在指定的模块路径(根目录)或类加载器loader关联的类路径(根目录)下查找匹配的资源;如果成功找到资源,则返回其入流
return ((BuiltinClassLoader) loader).findResourceAsStream(mn, resName);
} else {
// 如果loader是自定义的类加载器,则在loader可以访问到的模块路径或类路径的根目录下查找匹配的资源
URL url = loader.findResource(mn, resName);
if(url != null) {
try {
return url.openStream();
} catch(SecurityException ignored) {
}
}
}
return null;
}
/*▲ 关联信息 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ reads ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Indicates if this module reads the given module.
* This method returns {@code true} if invoked to test if this module reads itself.
* It also returns {@code true} if invoked on an unnamed module (as unnamed modules read all modules).
*
* @param other The other module
*
* @return {@code true} if this module reads {@code other}
*
* @see #addReads(Module)
*/
// 判断当前模块是否依赖(requires)other模块
public boolean canRead(Module other) {
Objects.requireNonNull(other);
// 未命名模块默认依赖所有模块
if(!this.isNamed()) {
return true; // an unnamed module reads all modules
}
// 模块依赖自身
if(other == this) {
return true; // all modules read themselves
}
// 如果other是命名模块,从静态配置中查找依赖(requires)信息
if(other.isNamed()) { // check if this module reads other
// 当前模块依赖(requires)哪些模块
Set<Module> reads = this.reads; // volatile read
if(reads != null && reads.contains(other)) {
return true;
}
}
// 从动态配置中查找依赖(requires)信息
if(ReflectionData.reads.containsKeyPair(this, other)) {
return true; // check if this module reads the other module reflectively
}
// 如果other是未命名模块,且当前模块依赖所有未命名模块
if(!other.isNamed() && ReflectionData.reads.containsKeyPair(this, ALL_UNNAMED_MODULE)) {
return true; // if other is an unnamed module then check if this module reads all unnamed modules
}
return false;
}
/**
* If the caller's module is this module then update this module to read
* the given module.
*
* This method is a no-op if {@code other} is this module (all modules read
* themselves), this module is an unnamed module (as unnamed modules read
* all modules), or this module already reads {@code other}.
*
* @param other The other module
*
* @return this module
*
* @throws IllegalCallerException If this is a named module and the caller's module is not this
* module
* @implNote <em>Read edges</em> added by this method are <em>weak</em> and
* do not prevent {@code other} from being GC'ed when this module is
* strongly reachable.
* @see #canRead
*/
// (动态配置)使当前模块依赖(requires)other模块(必须在当前模块内调用)
@CallerSensitive
public Module addReads(Module other) {
Objects.requireNonNull(other);
// 未命名模块依赖(requires)所有模块
if(!isNamed()) {
return this;
}
// 获取addReads()的调用者所处的类
Class<?> callerClass = Reflection.getCallerClass();
// 获取callerClass所处的模块
Module caller = getCallerModule(callerClass);
// 必须保证addReads()方法在当前命名模块中调用
if(caller != this) {
throw new IllegalCallerException(caller + " != " + this);
}
// 使当前模块依赖(requires)other模块,需要通知VM
implAddReads(other, true);
return this;
}
/*▲ reads ████████████████████████████████████████████████████████████████████████████████┛ */
/*
* exports: 类之间允许显式访问,且允许访问public元素,包括反射,通常与requires配合使用
* opens :
* 编译时 - 无作用
* 运行时 - 类之间允许显式访问,且允许访问非public元素,包括反射
*
* 注:在运行时,opens行为会覆盖exports行为
*/
/*▼ exports ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns {@code true} if this module exports the given package
* unconditionally.
*
* <p> This method always returns {@code true} when invoked on an unnamed
* module. A package that is {@link #isOpen(String) opened} unconditionally
* is considered exported unconditionally at run-time and so this method
* returns {@code true} if the package is opened unconditionally. </p>
*
* <p> This method does not check if the given module reads this module. </p>
*
* @param pn The package name
*
* @return {@code true} if this module exports the package unconditionally
*
* @see ModuleDescriptor#exports()
*/
// 判断当前模块是否将pn包导出(exports)给了所有模块
public boolean isExported(String pn) {
Objects.requireNonNull(pn);
return implIsExportedOrOpen(pn, EVERYONE_MODULE, /*open*/false);
}
/**
* Returns {@code true} if this module exports the given package to at
* least the given module.
*
* <p> This method returns {@code true} if invoked to test if a package in
* this module is exported to itself. It always returns {@code true} when
* invoked on an unnamed module. A package that is {@link #isOpen open} to
* the given module is considered exported to that module at run-time and
* so this method returns {@code true} if the package is open to the given
* module. </p>
*
* <p> This method does not check if the given module reads this module. </p>
*
* @param pn The package name
* @param other The other module
*
* @return {@code true} if this module exports the package to at least the
* given module
*
* @see ModuleDescriptor#exports()
* @see #addExports(String, Module)
*/
// 判断当前模块是否将pn包导出(exports)给了other模块
public boolean isExported(String pn, Module other) {
Objects.requireNonNull(pn);
Objects.requireNonNull(other);
return implIsExportedOrOpen(pn, other, /*open*/false);
}
/**
* If the caller's module is this module then update this module to export
* the given package to the given module.
*
* <p> This method has no effect if the package is already exported (or
* <em>open</em>) to the given module. </p>
*
* @param pn The package name
* @param other The module
*
* @return this module
*
* @throws IllegalArgumentException If {@code pn} is {@code null}, or this is a named module and the
* package {@code pn} is not a package in this module
* @throws IllegalCallerException If this is a named module and the caller's module is not this
* module
* @apiNote As specified in section 5.4.3 of the <cite>The Java™
* Virtual Machine Specification </cite>, if an attempt to resolve a
* symbolic reference fails because of a linkage error, then subsequent
* attempts to resolve the reference always fail with the same error that
* was thrown as a result of the initial resolution attempt.
* @jvms 5.4.3 Resolution
* @see #isExported(String, Module)
*/
// (动态配置)将当前模块的pn包导出(exports)给other模块(必须在当前模块内调用)
@CallerSensitive
public Module addExports(String pn, Module other) {
if(pn == null) {
throw new IllegalArgumentException("package is null");
}
Objects.requireNonNull(other);
// 未命名模块导出(exports)所有包
if(!isNamed()) {
return this;
}
// 获取addExports()的调用者所处的类
Class<?> callerClass = Reflection.getCallerClass();
// 获取callerClass所处的模块
Module caller = getCallerModule(callerClass);
// 必须保证addExports()方法在当前命名模块中调用
if(caller != this) {
throw new IllegalCallerException(caller + " != " + this);
}
// 将当前模块的pn包导出(exports)给other模块,需要通知VM
implAddExportsOrOpens(pn, other, /*open*/false, /*syncVM*/true);
return this;
}
/*▲ exports ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ opens ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns {@code true} if this module has <em>opened</em> a package
* unconditionally.
*
* <p> This method always returns {@code true} when invoked on an unnamed
* module. Additionally, it always returns {@code true} when invoked on an
* {@link ModuleDescriptor#isOpen open} module with a package in the
* module. </p>
*
* <p> This method does not check if the given module reads this module. </p>
*
* @param pn The package name
*
* @return {@code true} if this module has <em>opened</em> the package
* unconditionally
*
* @see ModuleDescriptor#opens()
*/
// 判断当前模块是否将pn包(开放)opens给了所有模块
public boolean isOpen(String pn) {
Objects.requireNonNull(pn);
return implIsExportedOrOpen(pn, EVERYONE_MODULE, /*open*/true);
}
/**
* Returns {@code true} if this module has <em>opened</em> a package to at
* least the given module.
*
* <p> This method returns {@code true} if invoked to test if a package in
* this module is open to itself. It returns {@code true} when invoked on an
* {@link ModuleDescriptor#isOpen open} module with a package in the module.
* It always returns {@code true} when invoked on an unnamed module. </p>
*
* <p> This method does not check if the given module reads this module. </p>
*
* @param pn The package name
* @param other The other module
*
* @return {@code true} if this module has <em>opened</em> the package
* to at least the given module
*
* @see ModuleDescriptor#opens()
* @see #addOpens(String, Module)
* @see java.lang.reflect.AccessibleObject#setAccessible(boolean)
* @see java.lang.invoke.MethodHandles#privateLookupIn
*/
// 判断当前模块是否将pn包(开放)opens给了other模块
public boolean isOpen(String pn, Module other) {
Objects.requireNonNull(pn);
Objects.requireNonNull(other);
return implIsExportedOrOpen(pn, other, /*open*/true);
}
/**
* If this module has <em>opened</em> a package to at least the caller
* module then update this module to open the package to the given module.
* Opening a package with this method allows all types in the package,
* and all their members, not just public types and their public members,
* to be reflected on by the given module when using APIs that support
* private access or a way to bypass or suppress default Java language
* access control checks.
*
* <p> This method has no effect if the package is already <em>open</em>
* to the given module. </p>
*
* @param pn The package name
* @param other The module
*
* @return this module
*
* @throws IllegalArgumentException If {@code pn} is {@code null}, or this is a named module and the
* package {@code pn} is not a package in this module
* @throws IllegalCallerException If this is a named module and this module has not opened the
* package to at least the caller's module
* @apiNote This method can be used for cases where a <em>consumer
* module</em> uses a qualified opens to open a package to an <em>API
* module</em> but where the reflective access to the members of classes in
* the consumer module is delegated to code in another module. Code in the
* API module can use this method to open the package in the consumer module
* to the other module.
* @see #isOpen(String, Module)
* @see java.lang.reflect.AccessibleObject#setAccessible(boolean)
* @see java.lang.invoke.MethodHandles#privateLookupIn
*/
// (动态配置)将当前模块的pn包(开放)opens给other模块(必须在当前模块内调用)
@CallerSensitive
public Module addOpens(String pn, Module other) {
if(pn == null) {
throw new IllegalArgumentException("package is null");
}
Objects.requireNonNull(other);
// 未命名模块(开放)opens所有包
if(!isNamed()) {
return this;
}
// 获取addOpens()的调用者所处的类
Class<?> callerClass = Reflection.getCallerClass();
// 获取callerClass所处的模块
Module caller = getCallerModule(callerClass);
// 必须保证addOpens()方法在当前命名模块中调用
if(caller != this && (caller == null || !isOpen(pn, caller))) {
throw new IllegalCallerException(pn + " is not open to " + caller);
}
// 将当前模块的pn包(开放)opens给other模块,需要通知VM
implAddExportsOrOpens(pn, other, /*open*/true, /*syncVM*/true);
return this;
}
/*▲ opens ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ uses ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* If the caller's module is this module then update this module to add a
* service dependence on the given service type. This method is intended
* for use by frameworks that invoke {@link java.util.ServiceLoader
* ServiceLoader} on behalf of other modules or where the framework is
* passed a reference to the service type by other code. This method is
* a no-op when invoked on an unnamed module or an automatic module.
*
* <p> This method does not cause {@link Configuration#resolveAndBind
* resolveAndBind} to be re-run. </p>
*
* @param service The service type
*
* @return this module
*
* @throws IllegalCallerException If this is a named module and the caller's module is not this
* module
* @see #canUse(Class)
* @see ModuleDescriptor#uses()
*/
// (动态配置)声明当前模块将使用(uses)指定的服务(必须在当前模块内调用)
@CallerSensitive
public Module addUses(Class<?> service) {
Objects.requireNonNull(service);
// 如果是未命名模块,或者是自动模块,直接返回
if(!isNamed() || descriptor.isAutomatic()) {
// 未命名模块或自动模块可以使用所有注册的服务
return this;
}
// 获取addUses()的调用者所处的类
Class<?> callerClass = Reflection.getCallerClass();
// 获取callerClass所处的模块
Module caller = getCallerModule(callerClass);
// 必须保证addOpens()方法在当前命名模块中调用
if(caller != this) {
throw new IllegalCallerException(caller + " != " + this);
}
// 声明当前模块将使用(uses)指定的服务
implAddUses(service);
return this;
}
/**
* Indicates if this module has a service dependence on the given service type.
* This method always returns {@code true} when invoked on an unnamed module or an automatic module.
*
* @param service The service type
*
* @return {@code true} if this module uses service type {@code st}
*
* @see #addUses(Class)
*/
// 判断当前模块是否声明使用(uses)指定的服务
public boolean canUse(Class<?> service) {
Objects.requireNonNull(service);
// 未命名模块可使用(uses)所有服务
if(!isNamed()) {
return true;
}
// 自动模块可使用(uses)所有服务
if(descriptor.isAutomatic()) {
return true;
}
// uses was declared
if(descriptor.uses().contains(service.getName())) {
// 存在静态声明
return true;
}
// uses added via addUses
if(ReflectionData.uses.containsKeyPair(this, service)) {
// 存在动态声明
return true;
}
return false;
}
/*▲ uses ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 注解 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* {@inheritDoc}
* This method returns an empty array when invoked on an unnamed module.
*/
// 1-1 返回当前模块上所有类型的注解
@Override
public Annotation[] getAnnotations() {
return moduleInfoClass().getAnnotations();
}
/**
* {@inheritDoc}
* This method returns {@code null} when invoked on an unnamed module.
*/
// 1-2 返回当前模块上指定类型的注解
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
return moduleInfoClass().getDeclaredAnnotation(annotationClass);
}
/**
* {@inheritDoc}
* This method returns an empty array when invoked on an unnamed module.
*/
// 2-1 返回当前模块上所有类型的注解
@Override
public Annotation[] getDeclaredAnnotations() {
return moduleInfoClass().getDeclaredAnnotations();
}
/*▲ 注解 ████████████████████████████████████████████████████████████████████████████████┛ */
/**
* Returns the string representation of this module. For a named module,
* the representation is the string {@code "module"}, followed by a space,
* and then the module name. For an unnamed module, the representation is
* the string {@code "unnamed module"}, followed by a space, and then an
* implementation specific string that identifies the unnamed module.
*
* @return The string representation of this module
*/
@Override
public String toString() {
if(isNamed()) {
return "module " + name;
} else {
String id = Integer.toHexString(System.identityHashCode(this));
return "unnamed module @" + id;
}
}
/**
* Returns the module that a given caller class is a member of. Returns
* {@code null} if the caller is {@code null}.
*/
// 获取callerClass所在的模块,如果callerClass为null,则返回null
private Module getCallerModule(Class<?> callerClass) {
return (callerClass != null) ? callerClass.getModule() : null;
}
/**
* Updates this module to read another module.
*
* @apiNote Used by the --add-reads command line option.
*/
// 使当前模块依赖(requires)other模块,需要通知VM
void implAddReads(Module other) {
implAddReads(other, true);
}
/**
* Updates this module to read all unnamed modules.
*
* @apiNote Used by the --add-reads command line option.
*/
// 使当前模块依赖(requires)所有未命名模块,需要通知VM
void implAddReadsAllUnnamed() {
implAddReads(Module.ALL_UNNAMED_MODULE, true);
}
/**
* Updates this module to read another module without notifying the VM.
*
* @apiNote This method is for VM white-box testing.
*/
// 使当前模块依赖(requires)other模块,不需要通知VM(仅用于测试)
void implAddReadsNoSync(Module other) {
implAddReads(other, false);
}
/**
* Makes the given {@code Module} readable to this module.
*
* If {@code syncVM} is {@code true} then the VM is notified.
*/
// 使当前模块依赖(requires)other模块,syncVM决定是否通知VM
private void implAddReads(Module other, boolean syncVM) {
Objects.requireNonNull(other);
// 如果当前模块依赖(requires)other模块
if(canRead(other)) {
return;
}
// update VM first, just in case it fails
if(syncVM) {
// 如果other代表所有未命名模块
if(other == ALL_UNNAMED_MODULE) {
addReads0(this, null);
} else {
addReads0(this, other);
}
}
// add reflective read
ReflectionData.reads.putIfAbsent(this, other, Boolean.TRUE);
}
/**
* Returns {@code true} if this module reflectively exports the given package to the given module.