-
Notifications
You must be signed in to change notification settings - Fork 668
/
ResourceBundle.java
4197 lines (3834 loc) · 192 KB
/
ResourceBundle.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, 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.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package java.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
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.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.jar.JarEntry;
import java.util.spi.ResourceBundleControlProvider;
import java.util.spi.ResourceBundleProvider;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jdk.internal.loader.BootLoader;
import jdk.internal.misc.JavaUtilResourceBundleAccess;
import jdk.internal.misc.SharedSecrets;
import jdk.internal.reflect.CallerSensitive;
import jdk.internal.reflect.Reflection;
import sun.security.action.GetPropertyAction;
import sun.util.locale.BaseLocale;
import sun.util.locale.LocaleObjectCache;
import static sun.security.util.SecurityConstants.GET_CLASSLOADER_PERMISSION;
/**
* Resource bundles contain locale-specific objects. When your program needs a
* locale-specific resource, a <code>String</code> for example, your program can
* load it from the resource bundle that is appropriate for the current user's
* locale. In this way, you can write program code that is largely independent
* of the user's locale isolating most, if not all, of the locale-specific
* information in resource bundles.
*
* <p>
* This allows you to write programs that can:
* <UL>
* <LI> be easily localized, or translated, into different languages
* <LI> handle multiple locales at once
* <LI> be easily modified later to support even more locales
* </UL>
*
* <P>
* Resource bundles belong to families whose members share a common base
* name, but whose names also have additional components that identify
* their locales. For example, the base name of a family of resource
* bundles might be "MyResources". The family should have a default
* resource bundle which simply has the same name as its family -
* "MyResources" - and will be used as the bundle of last resort if a
* specific locale is not supported. The family can then provide as
* many locale-specific members as needed, for example a German one
* named "MyResources_de".
*
* <P>
* Each resource bundle in a family contains the same items, but the items have
* been translated for the locale represented by that resource bundle.
* For example, both "MyResources" and "MyResources_de" may have a
* <code>String</code> that's used on a button for canceling operations.
* In "MyResources" the <code>String</code> may contain "Cancel" and in
* "MyResources_de" it may contain "Abbrechen".
*
* <P>
* If there are different resources for different countries, you
* can make specializations: for example, "MyResources_de_CH" contains objects for
* the German language (de) in Switzerland (CH). If you want to only
* modify some of the resources
* in the specialization, you can do so.
*
* <P>
* When your program needs a locale-specific object, it loads
* the <code>ResourceBundle</code> class using the
* {@link #getBundle(java.lang.String, java.util.Locale) getBundle}
* method:
* <blockquote>
* <pre>
* ResourceBundle myResources =
* ResourceBundle.getBundle("MyResources", currentLocale);
* </pre>
* </blockquote>
*
* <P>
* Resource bundles contain key/value pairs. The keys uniquely
* identify a locale-specific object in the bundle. Here's an
* example of a <code>ListResourceBundle</code> that contains
* two key/value pairs:
* <blockquote>
* <pre>
* public class MyResources extends ListResourceBundle {
* protected Object[][] getContents() {
* return new Object[][] {
* // LOCALIZE THE SECOND STRING OF EACH ARRAY (e.g., "OK")
* {"OkKey", "OK"},
* {"CancelKey", "Cancel"},
* // END OF MATERIAL TO LOCALIZE
* };
* }
* }
* </pre>
* </blockquote>
* Keys are always <code>String</code>s.
* In this example, the keys are "OkKey" and "CancelKey".
* In the above example, the values
* are also <code>String</code>s--"OK" and "Cancel"--but
* they don't have to be. The values can be any type of object.
*
* <P>
* You retrieve an object from resource bundle using the appropriate
* getter method. Because "OkKey" and "CancelKey"
* are both strings, you would use <code>getString</code> to retrieve them:
* <blockquote>
* <pre>
* button1 = new Button(myResources.getString("OkKey"));
* button2 = new Button(myResources.getString("CancelKey"));
* </pre>
* </blockquote>
* The getter methods all require the key as an argument and return
* the object if found. If the object is not found, the getter method
* throws a <code>MissingResourceException</code>.
*
* <P>
* Besides <code>getString</code>, <code>ResourceBundle</code> also provides
* a method for getting string arrays, <code>getStringArray</code>,
* as well as a generic <code>getObject</code> method for any other
* type of object. When using <code>getObject</code>, you'll
* have to cast the result to the appropriate type. For example:
* <blockquote>
* <pre>
* int[] myIntegers = (int[]) myResources.getObject("intList");
* </pre>
* </blockquote>
*
* <P>
* The Java Platform provides two subclasses of <code>ResourceBundle</code>,
* <code>ListResourceBundle</code> and <code>PropertyResourceBundle</code>,
* that provide a fairly simple way to create resources.
* As you saw briefly in a previous example, <code>ListResourceBundle</code>
* manages its resource as a list of key/value pairs.
* <code>PropertyResourceBundle</code> uses a properties file to manage
* its resources.
*
* <p>
* If <code>ListResourceBundle</code> or <code>PropertyResourceBundle</code>
* do not suit your needs, you can write your own <code>ResourceBundle</code>
* subclass. Your subclasses must override two methods: <code>handleGetObject</code>
* and <code>getKeys()</code>.
*
* <p>
* The implementation of a {@code ResourceBundle} subclass must be thread-safe
* if it's simultaneously used by multiple threads. The default implementations
* of the non-abstract methods in this class, and the methods in the direct
* known concrete subclasses {@code ListResourceBundle} and
* {@code PropertyResourceBundle} are thread-safe.
*
* <h3><a id="resource-bundle-modules">Resource Bundles and Named Modules</a></h3>
*
* Resource bundles can be deployed in modules in the following ways:
*
* <h4>Resource bundles together with an application</h4>
*
* Resource bundles can be deployed together with an application in the same
* module. In that case, the resource bundles are loaded
* by code in the module by calling the {@link #getBundle(String)}
* or {@link #getBundle(String, Locale)} method.
*
* <h4><a id="service-providers">Resource bundles as service providers</a></h4>
*
* Resource bundles can be deployed in one or more <em>service provider modules</em>
* and they can be located using {@link ServiceLoader}.
* A {@linkplain ResourceBundleProvider service} interface or class must be
* defined. The caller module declares that it uses the service, the service
* provider modules declare that they provide implementations of the service.
* Refer to {@link ResourceBundleProvider} for developing resource bundle
* services and deploying resource bundle providers.
* The module obtaining the resource bundle can be a resource bundle
* provider itself; in which case this module only locates the resource bundle
* via service provider mechanism.
*
* <p>A {@linkplain ResourceBundleProvider resource bundle provider} can
* provide resource bundles in any format such XML which replaces the need
* of {@link Control ResourceBundle.Control}.
*
* <h4><a id="other-modules">Resource bundles in other modules and class path</a></h4>
*
* Resource bundles in a named module may be <em>encapsulated</em> so that
* it cannot be located by code in other modules. Resource bundles
* in unnamed modules and class path are open for any module to access.
* Resource bundle follows the resource encapsulation rules as specified
* in {@link Module#getResourceAsStream(String)}.
*
* <p>The {@code getBundle} factory methods with no {@code Control} parameter
* locate and load resource bundles from
* {@linkplain ResourceBundleProvider service providers}.
* It may continue the search as if calling {@link Module#getResourceAsStream(String)}
* to find the named resource from a given module and calling
* {@link ClassLoader#getResourceAsStream(String)}; refer to
* the specification of the {@code getBundle} method for details.
* Only non-encapsulated resource bundles of "{@code java.class}"
* or "{@code java.properties}" format are searched.
*
* <p>If the caller module is a
* <a href="{@docRoot}/java.base/java/util/spi/ResourceBundleProvider.html#obtain-resource-bundle">
* resource bundle provider</a>, it does not fall back to the
* class loader search.
*
* <h4>Resource bundles in automatic modules</h4>
*
* A common format of resource bundles is in {@linkplain PropertyResourceBundle
* .properties} file format. Typically {@code .properties} resource bundles
* are packaged in a JAR file. Resource bundle only JAR file can be readily
* deployed as an <a href="{@docRoot}/java.base/java/lang/module/ModuleFinder.html#automatic-modules">
* automatic module</a>. For example, if the JAR file contains the
* entry "{@code p/q/Foo_ja.properties}" and no {@code .class} entry,
* when resolved and defined as an automatic module, no package is derived
* for this module. This allows resource bundles in {@code .properties}
* format packaged in one or more JAR files that may contain entries
* in the same directory and can be resolved successfully as
* automatic modules.
*
* <h3>ResourceBundle.Control</h3>
*
* The {@link ResourceBundle.Control} class provides information necessary
* to perform the bundle loading process by the <code>getBundle</code>
* factory methods that take a <code>ResourceBundle.Control</code>
* instance. You can implement your own subclass in order to enable
* non-standard resource bundle formats, change the search strategy, or
* define caching parameters. Refer to the descriptions of the class and the
* {@link #getBundle(String, Locale, ClassLoader, Control) getBundle}
* factory method for details.
*
* <p> {@link ResourceBundle.Control} is designed for an application deployed
* in an unnamed module, for example to support resource bundles in
* non-standard formats or package localized resources in a non-traditional
* convention. {@link ResourceBundleProvider} is the replacement for
* {@code ResourceBundle.Control} when migrating to modules.
* {@code UnsupportedOperationException} will be thrown when a factory
* method that takes the {@code ResourceBundle.Control} parameter is called.
*
* <p><a id="modify_default_behavior">For the {@code getBundle} factory</a>
* methods that take no {@link Control} instance, their <a
* href="#default_behavior"> default behavior</a> of resource bundle loading
* can be modified with custom {@link
* ResourceBundleControlProvider} implementations.
* If any of the
* providers provides a {@link Control} for the given base name, that {@link
* Control} will be used instead of the default {@link Control}. If there is
* more than one service provider for supporting the same base name,
* the first one returned from {@link ServiceLoader} will be used.
* A custom {@link Control} implementation is ignored by named modules.
*
* <h3>Cache Management</h3>
*
* Resource bundle instances created by the <code>getBundle</code> factory
* methods are cached by default, and the factory methods return the same
* resource bundle instance multiple times if it has been
* cached. <code>getBundle</code> clients may clear the cache, manage the
* lifetime of cached resource bundle instances using time-to-live values,
* or specify not to cache resource bundle instances. Refer to the
* descriptions of the {@linkplain #getBundle(String, Locale, ClassLoader,
* Control) <code>getBundle</code> factory method}, {@link
* #clearCache(ClassLoader) clearCache}, {@link
* Control#getTimeToLive(String, Locale)
* ResourceBundle.Control.getTimeToLive}, and {@link
* Control#needsReload(String, Locale, String, ClassLoader, ResourceBundle,
* long) ResourceBundle.Control.needsReload} for details.
*
* <h3>Example</h3>
*
* The following is a very simple example of a <code>ResourceBundle</code>
* subclass, <code>MyResources</code>, that manages two resources (for a larger number of
* resources you would probably use a <code>Map</code>).
* Notice that you don't need to supply a value if
* a "parent-level" <code>ResourceBundle</code> handles the same
* key with the same value (as for the okKey below).
* <blockquote>
* <pre>
* // default (English language, United States)
* public class MyResources extends ResourceBundle {
* public Object handleGetObject(String key) {
* if (key.equals("okKey")) return "Ok";
* if (key.equals("cancelKey")) return "Cancel";
* return null;
* }
*
* public Enumeration<String> getKeys() {
* return Collections.enumeration(keySet());
* }
*
* // Overrides handleKeySet() so that the getKeys() implementation
* // can rely on the keySet() value.
* protected Set<String> handleKeySet() {
* return new HashSet<String>(Arrays.asList("okKey", "cancelKey"));
* }
* }
*
* // German language
* public class MyResources_de extends MyResources {
* public Object handleGetObject(String key) {
* // don't need okKey, since parent level handles it.
* if (key.equals("cancelKey")) return "Abbrechen";
* return null;
* }
*
* protected Set<String> handleKeySet() {
* return new HashSet<String>(Arrays.asList("cancelKey"));
* }
* }
* </pre>
* </blockquote>
* You do not have to restrict yourself to using a single family of
* <code>ResourceBundle</code>s. For example, you could have a set of bundles for
* exception messages, <code>ExceptionResources</code>
* (<code>ExceptionResources_fr</code>, <code>ExceptionResources_de</code>, ...),
* and one for widgets, <code>WidgetResource</code> (<code>WidgetResources_fr</code>,
* <code>WidgetResources_de</code>, ...); breaking up the resources however you like.
*
* @revised 9
* @spec JPMS
* @see ListResourceBundle
* @see PropertyResourceBundle
* @see MissingResourceException
* @see ResourceBundleProvider
* @since 1.1
*/
/*
* 资源集
*/
public abstract class ResourceBundle {
/** initial size of the bundle cache */
private static final int INITIAL_CACHE_SIZE = 32;
/** constant indicating that no resource bundle exists */
// 占位符,用来表示一个空资源
private static final ResourceBundle NONEXISTENT_BUNDLE = new ResourceBundle() {
public Enumeration<String> getKeys() {
return null;
}
public String toString() {
return "NONEXISTENT_BUNDLE";
}
protected Object handleGetObject(String key) {
return null;
}
};
/**
* The parent bundle of this bundle.
* The parent bundle is searched by {@link #getObject getObject}
* when this bundle does not contain a particular resource.
*/
// 该资源在资源链上的父级资源
protected ResourceBundle parent = null;
/*
* Queue for reference objects referring to class loaders or bundles.
*
* 引用队列
*
* 这个引用队列很忙啊,
* 既存储BundleReference这种类型的软引用,
* 又存储KeyElementReference这种类型的弱引用。
* 好在这两种类型都是以类似键值对的形式存在,且键的类型是CacheKey
* 而且,这两种类型实现了共同的接口:CacheKeyReference
* 这个接口有个getCacheKey()方法,可以取出进入ReferenceQueue的"报废引用"包含的key,即CacheKey
* 进而,释放CacheKey指向的内存
*/
private static final ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
/**
* The cache is a map from cache keys (with bundle base name, locale, and class loader)
* to either a resource bundle or NONEXISTENT_BUNDLE wrapped by a BundleReference.
*
* The cache is a ConcurrentMap, allowing the cache to be searched concurrently by multiple threads.
* This will also allow the cache keys to be reclaimed along with the ClassLoaders they reference.
*
* This variable would be better named "cache",
* but we keep the old name for compatibility with some workarounds for bug 4212439.
*/
// 这里笼统地称为【资源缓存】,实际上这里缓存的是资源引用BundleReference
private static final ConcurrentMap<CacheKey, BundleReference> cacheList = new ConcurrentHashMap<>(INITIAL_CACHE_SIZE);
private static final String UNKNOWN_FORMAT = "";
private static final boolean TRACE_ON = Boolean.valueOf(GetPropertyAction.privilegedGetProperty("resource.bundle.debug", "false"));
/** The flag indicating this bundle has expired in the cache. */
private volatile boolean expired;
/** The back link to the cache key. null if this bundle isn't in the cache (yet) or has expired. */
private volatile CacheKey cacheKey;
/** A Set of the keys contained only in this ResourceBundle. */
private volatile Set<String> keySet;
/** The locale for this bundle. */
private Locale locale = null;
/** The base bundle name for this bundle. */
private String name;
// 预留一些后门方法
static {
SharedSecrets.setJavaUtilResourceBundleAccess(new JavaUtilResourceBundleAccess() {
@Override
public void setParent(ResourceBundle bundle, ResourceBundle parent) {
bundle.setParent(parent);
}
@Override
public ResourceBundle getParent(ResourceBundle bundle) {
return bundle.parent;
}
@Override
public void setLocale(ResourceBundle bundle, Locale locale) {
bundle.locale = locale;
}
@Override
public void setName(ResourceBundle bundle, String name) {
bundle.name = name;
}
@Override
public ResourceBundle getBundle(String baseName, Locale locale, Module module) {
// use the given module as the caller to bypass the access check
return getBundleImpl(module, module, baseName, locale, getDefaultControl(module, baseName));
}
@Override
public ResourceBundle newResourceBundle(Class<? extends ResourceBundle> bundleClass) {
return ResourceBundleProviderHelper.newResourceBundle(bundleClass);
}
});
}
/*▼ 构造方法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Sole constructor. (For invocation by subclass constructors, typically
* implicit.)
*/
public ResourceBundle() {
}
/*▲ 构造方法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 加载ResourceBundle ████████████████████████████████████████████████████████████████████████████████┓ */
/*
* 总结:
*
* 术语约定:
* 命名module:包括明确命名的module与自动module
* 【caller】:申请加载资源的类
* 【callerModule】:代指申请加载资源的类所在的module
* 【module】:代指搜索资源的入口module
*
* 这里总共有12个加载资源的方法,其中有public权限的是8个,简介如下:
*
* 关于Locale的支持:
* 【1-1-1-1】【1-1-1-2】【1-2-1】只支持使用当地默认的Locale信息
* 【1-1-1-3】【1-1-1-4】【1-1-2】【1-1-3】【1-2-2】支持预设Locale信息
*
* 关于资源文件的格式支持:
* 如果仅需要处理.class或.properties资源,每个public方法都可用。
*
* 如果需要处理其他格式的资源,比如处理国际化的xml资源,则:
* 1.轻量级方式:自定义Control创建Bundle的逻辑:
* 1.1 使用【1-1-1-2】【1-1-1-4】【1-1-3】,从形参传入自定义的Control,不过这三个方法要求【callerModule】未命名(此时【module】也被设置为未命名)
* 1.2 使用【1-1-1-1】【1-1-1-2】【1-1-1-3】【1-1-1-4】【1-1-2】【1-1-3】,并且实现ResourceBundleControlProvider服务来提供Control
* 使用这种方式要求【callerModule】未命名(此时【module】也被设置为未命名)
* 1.3 使用【1-2-1】【1-2-2】,且要求【module】未命名(对【callerModule】没要求)(通过XXX.class.getClassLoader().getUnnamedModule()来实现)
* 使用这种方式也需要实现ResourceBundleControlProvider服务,以提供Control
* 2.重量级方式:实现ResourceBundleProvider这个服务接口,提供ResourceBundle实例
* 该方式要求【module】处于命名module,换句话说,需要经过【1-2-1】【1-2-2】实现
*
* 无论哪个方法,其Locale参数和Control参数均不应为null
*
* 如果资源位于命名模块中,看情况设置其open权限和exports权限给读取资源的模块
*
*/
/*
* ▶ 1
*
* 所有加载ResourceBundle的方法最终都进入了这个方法
*
* callerModule 【caller】所在的module
* module 搜索资源的入口
* baseName 待加载资源的全限定名
* locale 待加载的资源的本地化信息
* control 控制器,进行资源加载操作
*
* 关于module:
* 资源可能在该module中,也可能不在
* 如果该module是命名module,则后续先尝试在此module中搜索资源
* 如果该module是未命名module,则后续会先获取定义该module的ClassLoader,
* 然后依次遍历该ClassLoader的命名module和未命名module,以搜索目标资源
*/
private static ResourceBundle getBundleImpl(Module callerModule, Module module, String baseName, Locale locale, Control control) {
if(locale == null || control == null) {
throw new NullPointerException();
}
/*
* We create a CacheKey here for use by this call.
* The base name and modules will never change during the bundle loading process.
* We have to make sure that the locale is set before using it as a cache key.
*
* 对当前ResourceBundle实例的基本信息做一个记录
* 后续会将该记录与当前的资源实例关联起来缓存到cacheList
*
* 记录中包含baseName, locale, module, callerModule信息
* 其中,module和callerModule会被弱引用追踪
*/
CacheKey cacheKey = new CacheKey(baseName, locale, module, callerModule);
ResourceBundle bundle = null;
// 从之前的缓存映射中搜索ResourceBundle实例
BundleReference bundleRef = cacheList.get(cacheKey);
if(bundleRef != null) {
bundle = bundleRef.get();
bundleRef = null;
}
/*
* If this bundle and all of its parents are valid (not expired), then return this bundle.
* If any of the bundles is expired, we don't call control.needsReload here
* but instead drop into the complete loading process below.
*
* 只有整个资源链上的资源仍然有效,才返回这个Bundle,否则需要重新搜索
*/
if(isValidBundle(bundle) // 验证Bundle是否有效
&& hasValidParentChain(bundle)) { // 验证资源链上的父级资源是否仍然有效
return bundle;
}
/*
* No valid bundle was found in the cache, so we need to load the resource bundle and its parents
*
* 在缓存中找不到有效的bundle,或者缓存的资源链存在过期现象,则我们需要重新加载资源包
*/
// 是否为已知的特定Control
boolean isKnownControl = (control == Control.INSTANCE) || (control instanceof SingleFormatControl);
// 获取当前Control可以识别的资源格式
List<String> formats = control.getFormats(baseName);
// 如果是自定义的Control,要确保formats有效
if(!isKnownControl // 是否为已知的特定Control
&& !checkList(formats)) { // 验证formats列表是否有效。有效的formats列表不为null,且不包含null元素
throw new IllegalArgumentException("Invalid Control: getFormats");
}
/*
* 资源链起点
*
* 一个模糊的区域信息可能会匹配多个资源
* 所有查找到的匹配资源会串在一起,形成一条资源链
* baseBundle匹配Locale为Locale.ROOT的资源
*/
ResourceBundle baseBundle = null;
for(Locale targetLocale = locale; targetLocale != null; targetLocale = control.getFallbackLocale(baseName, targetLocale)) {
/*
* 获取匹配的Locale列表作为候选本地化信息
* 比如已知语言为zh,则可以匹配出{"zh", ""}两条Locale信息
* 已知语言为zh,区域为CN,则可以匹配出{"zh_CN_#Hans", "zh__#Hans", "zh_CN", "zh", ""}五条Locale信息
*/
List<Locale> candidateLocales = control.getCandidateLocales(baseName, targetLocale);
if(!isKnownControl // 是否为已知的特定Control
&& !checkList(candidateLocales)) { // 验证candidateLocales列表是否有效。有效的candidateLocales列表不为null,且不包含null元素
throw new IllegalArgumentException("Invalid Control: getCandidateLocales");
}
// ★★ 开始查找资源
bundle = findBundle(callerModule, module, cacheKey, candidateLocales, formats, 0, control, baseBundle);
/*
* If the loaded bundle is the base bundle and exactly for the requested locale or the only candidate locale,
* then take the bundle as the resulting one.
* If the loaded bundle is the base bundle,
* it's put on hold until we finish processing all fallback locales.
*/
// 验证资源是否有效
if(isValidBundle(bundle)) {
boolean isBaseBundle = Locale.ROOT.equals(bundle.locale);
if(!isBaseBundle || bundle.locale.equals(locale) || (candidateLocales.size() == 1 && bundle.locale.equals(candidateLocales.get(0)))) {
break;
}
// If the base bundle has been loaded,
// keep the reference in baseBundle so that we can avoid any redundant loading in case the control specify not to cache bundles.
if(isBaseBundle && baseBundle == null) {
baseBundle = bundle;
}
}
}
if(bundle == null) {
if(baseBundle == null) {
throwMissingResourceException(baseName, locale, cacheKey.getCause());
}
bundle = baseBundle;
}
// keep callerModule and module reachable for as long as we are operating with WeakReference(s) to them (in CacheKey)...
Reference.reachabilityFence(callerModule);
Reference.reachabilityFence(module);
return bundle;
}
/**
* This method will find resource bundles using the legacy mechanism
* if the caller is unnamed module or the given class loader is
* not the class loader of the caller module getting the resource
* bundle, i.e. find the class that is visible to the class loader
* and properties from unnamed module.
*
* The module-aware resource bundle lookup mechanism will load
* the service providers using the service loader mechanism
* as well as properties local in the caller module.
*/
/*
* ▶ 1-1
*
* baseName 待加载资源的全限定名
* locale 待加载的资源的本地化信息
* caller 申请加载资源的类
* loader 用于加载资源的ClassLoader(资源搜索基于该ClassLoader展开)
* control 控制器,进行资源加载操作
*/
private static ResourceBundle getBundleImpl(String baseName, Locale locale, Class<?> caller, ClassLoader loader, Control control) {
if(caller == null) {
throw new InternalError("null caller");
}
// 【caller】所在的module
Module callerModule = caller.getModule();
if(callerModule.isNamed() // 如果【callerModule】是命名模块
&& loader == getLoader(callerModule)) { // callerModule的ClassLoader与用于加载资源的ClassLoader一致
/*
* 将【module】设置为【callerModule】
* 即使后续在【callerModule】中找不到资源,
* 仍然可以通过指定的ClassLoader到真正包含资源的module再查找
*
* 这里为什么不先通过ClassLoader找出资源所在的module,然后再去查找?
* 个人猜想是优化操作,因为大多数加载本地化资源的行为发生在【callerModule】中
*/
return getBundleImpl(callerModule, callerModule, baseName, locale, control);
}
/*
* find resource bundles from unnamed module of given class loader
* Java agent can add to the bootclasspath
* e.g. via java.lang.instrument.Instrumentation and load classes in unnamed module.
* It may call RB::getBundle that will end up here with loader == null.
*/
/*
* 至此,有两种情况:
* 1. 【callerModule】是未命名模块
* 2. 【callerModule】是命名模块,但是【callerModule】的ClassLoader与用于加载资源的ClassLoader不一致
*
* 此时,无法确定待加载资源在哪个模块,也无法确定从哪个模块先搜索会比较省力
* 这种情形下,获取用于加载资源的ClassLoader中定义的未命名模块unnamedModule
* 当下面的getBundleImpl设置了unnamedModule形参后,
* 程序调用会辗转进入findBundle方法,
* 在findBundle方法内部,会判断如果unnamedModule是未命名模块,
* 那么系统将先从命名模块搜索中资源,如果找不到,再去未命名模块搜索
*/
Module unnamedModule = loader != null ? loader.getUnnamedModule() : BootLoader.getUnnamedModule();
return getBundleImpl(callerModule, unnamedModule, baseName, locale, control);
}
/*
* ▶ 1-1-1
*
* baseName 待加载资源的全限定名
* locale 待加载的资源的本地化信息
* caller 申请加载资源的类
* control 控制器,进行资源加载操作
*/
private static ResourceBundle getBundleImpl(String baseName, Locale locale, Class<?> caller, Control control) {
// 使用【caller】的ClassLoader作为加载资源的ClassLoader
return getBundleImpl(baseName, locale, caller, caller.getClassLoader(), control);
}
/**
* Gets a resource bundle using the specified base name, the default locale,
* and the caller module. Calling this method is equivalent to calling
* <blockquote>
* <code>getBundle(baseName, Locale.getDefault(), callerModule)</code>,
* </blockquote>
*
* @param baseName the base name of the resource bundle, a fully qualified class name
*
* @return a resource bundle for the given base name and the default locale
*
* @throws java.lang.NullPointerException if <code>baseName</code> is <code>null</code>
* @throws MissingResourceException if no resource bundle for the specified base name can be found
* @see <a href="#default_behavior">Resource Bundle Search and Loading Strategy</a>
* @see <a href="#resource-bundle-modules">Resource Bundles and Named Modules</a>
*/
/*
* ▶ 1-1-1-1
*
* baseName 待加载资源的全限定名
*
* 如果【callerModule】未命名,则可以使用默认的Control,
* 也可以实现ResourceBundleControlProviderHolder服务来自定义Control
* 否则,只能使用默认的Control
*/
@CallerSensitive
public static final ResourceBundle getBundle(String baseName) {
// 获取【caller】
Class<?> caller = Reflection.getCallerClass();
/*
* Locale.getDefault() 获取默认的本地化信息
* getDefaultControl(caller, baseName) 根据caller和baseName来确定一个Control
*/
return getBundleImpl(baseName, Locale.getDefault(), caller, getDefaultControl(caller, baseName));
}
/**
* Returns a resource bundle using the specified base name, the
* default locale and the specified control. Calling this method
* is equivalent to calling
* <pre>
* getBundle(baseName, Locale.getDefault(),
* this.getClass().getClassLoader(), control),
* </pre>
* except that <code>getClassLoader()</code> is run with the security
* privileges of <code>ResourceBundle</code>. See {@link
* #getBundle(String, Locale, ClassLoader, Control) getBundle} for the
* complete description of the resource bundle loading process with a
* <code>ResourceBundle.Control</code>.
*
* @param baseName the base name of the resource bundle, a fully qualified class
* name
* @param control the control which gives information for the resource bundle
* loading process
*
* @return a resource bundle for the given base name and the default locale
*
* @throws NullPointerException if <code>baseName</code> or <code>control</code> is
* <code>null</code>
* @throws MissingResourceException if no resource bundle for the specified base name can be found
* @throws IllegalArgumentException if the given <code>control</code> doesn't perform properly
* (e.g., <code>control.getCandidateLocales</code> returns null.)
* Note that validation of <code>control</code> is performed as
* needed.
* @throws UnsupportedOperationException if this method is called in a named module
* @revised 9
* @spec JPMS
* @since 1.6
*/
/*
* ▶ 1-1-1-2
*
* ★ 只能在未命名module中被调用
*
* baseName 待加载资源的全限定名
* control 控制器,进行资源加载操作
*/
@CallerSensitive
public static final ResourceBundle getBundle(String baseName, Control control) {
// 获取【caller】
Class<?> caller = Reflection.getCallerClass();
// 默认的本地化信息
Locale targetLocale = Locale.getDefault();
// 确保【callerModule】未命名
checkNamedModule(caller);
return getBundleImpl(baseName, targetLocale, caller, control);
}
/**
* Gets a resource bundle using the specified base name and locale,
* and the caller module. Calling this method is equivalent to calling
* <blockquote>
* <code>getBundle(baseName, locale, callerModule)</code>,
* </blockquote>
*
* @param baseName the base name of the resource bundle, a fully qualified class name
* @param locale the locale for which a resource bundle is desired
*
* @return a resource bundle for the given base name and locale
*
* @throws NullPointerException if <code>baseName</code> or <code>locale</code> is <code>null</code>
* @throws MissingResourceException if no resource bundle for the specified base name can be found
* @see <a href="#default_behavior">Resource Bundle Search and Loading Strategy</a>
* @see <a href="#resource-bundle-modules">Resource Bundles and Named Modules</a>
*/
/*
* ▶ 1-1-1-3
*
* baseName 待加载资源的全限定名
* locale 待加载的资源的本地化信息
*
* 如果【callerModule】未命名,则可以使用默认的Control,
* 也可以实现ResourceBundleControlProviderHolder服务来自定义Control
* 否则,只能使用默认的Control
*/
@CallerSensitive
public static final ResourceBundle getBundle(String baseName, Locale locale) {
// 获取【caller】
Class<?> caller = Reflection.getCallerClass();
// getDefaultControl(caller, baseName) 根据caller和baseName来确定一个Control
return getBundleImpl(baseName, locale, caller, getDefaultControl(caller, baseName));
}
/**
* Returns a resource bundle using the specified base name, target
* locale and control, and the caller's class loader. Calling this
* method is equivalent to calling
* <pre>
* getBundle(baseName, targetLocale, this.getClass().getClassLoader(),
* control),
* </pre>
* except that <code>getClassLoader()</code> is run with the security
* privileges of <code>ResourceBundle</code>. See {@link
* #getBundle(String, Locale, ClassLoader, Control) getBundle} for the
* complete description of the resource bundle loading process with a
* <code>ResourceBundle.Control</code>.
*
* @param baseName the base name of the resource bundle, a fully qualified
* class name
* @param targetLocale the locale for which a resource bundle is desired
* @param control the control which gives information for the resource
* bundle loading process
*
* @return a resource bundle for the given base name and a
* <code>Locale</code> in <code>locales</code>
*
* @throws NullPointerException if <code>baseName</code>, <code>locales</code> or
* <code>control</code> is <code>null</code>
* @throws MissingResourceException if no resource bundle for the specified base name in any
* of the <code>locales</code> can be found.
* @throws IllegalArgumentException if the given <code>control</code> doesn't perform properly
* (e.g., <code>control.getCandidateLocales</code> returns null.)
* Note that validation of <code>control</code> is performed as
* needed.
* @throws UnsupportedOperationException if this method is called in a named module
* @revised 9
* @spec JPMS
* @since 1.6
*/
/*
* ▶ 1-1-1-4
*
* ★ 只能在未命名module中被调用
*
* baseName 待加载资源的全限定名
* targetLocale 待加载的资源的本地化信息
* control 控制器,进行资源加载操作
*/
@CallerSensitive
public static final ResourceBundle getBundle(String baseName, Locale targetLocale, Control control) {
// 获取【caller】
Class<?> caller = Reflection.getCallerClass();
// 确保【callerModule】未命名
checkNamedModule(caller);
return getBundleImpl(baseName, targetLocale, caller, control);
}
/**
* Gets a resource bundle using the specified base name, locale, and class
* loader.
*
* <p>When this method is called from a named module and the given
* loader is the class loader of the caller module, this is equivalent
* to calling:
* <blockquote><pre>
* getBundle(baseName, targetLocale, callerModule)
* </pre></blockquote>
*
* otherwise, this is equivalent to calling:
* <blockquote><pre>
* getBundle(baseName, targetLocale, loader, control)
* </pre></blockquote>
* where {@code control} is the default instance of {@link Control} unless
* a {@code Control} instance is provided by
* {@link ResourceBundleControlProvider} SPI. Refer to the
* description of <a href="#modify_default_behavior">modifying the default
* behavior</a>. The following describes the default behavior.
*
* <p>
* <b><a id="default_behavior">Resource Bundle Search and Loading Strategy</a></b>
*
* <p><code>getBundle</code> uses the base name, the specified locale, and
* the default locale (obtained from {@link java.util.Locale#getDefault()
* Locale.getDefault}) to generate a sequence of <a
* id="candidates"><em>candidate bundle names</em></a>. If the specified
* locale's language, script, country, and variant are all empty strings,
* then the base name is the only candidate bundle name. Otherwise, a list
* of candidate locales is generated from the attribute values of the
* specified locale (language, script, country and variant) and appended to
* the base name. Typically, this will look like the following:
*
* <pre>
* baseName + "_" + language + "_" + script + "_" + country + "_" + variant
* baseName + "_" + language + "_" + script + "_" + country
* baseName + "_" + language + "_" + script
* baseName + "_" + language + "_" + country + "_" + variant
* baseName + "_" + language + "_" + country
* baseName + "_" + language
* </pre>
*
* <p>Candidate bundle names where the final component is an empty string
* are omitted, along with the underscore. For example, if country is an
* empty string, the second and the fifth candidate bundle names above
* would be omitted. Also, if script is an empty string, the candidate names
* including script are omitted. For example, a locale with language "de"
* and variant "JAVA" will produce candidate names with base name
* "MyResource" below.
*
* <pre>
* MyResource_de__JAVA
* MyResource_de
* </pre>
*
* In the case that the variant contains one or more underscores ('_'), a
* sequence of bundle names generated by truncating the last underscore and
* the part following it is inserted after a candidate bundle name with the
* original variant. For example, for a locale with language "en", script
* "Latn, country "US" and variant "WINDOWS_VISTA", and bundle base name