-
Notifications
You must be signed in to change notification settings - Fork 669
/
Copy pathAbstractChronology.java
894 lines (777 loc) · 41.4 KB
/
AbstractChronology.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
/*
* Copyright (c) 2012, 2013, 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.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time.chrono;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;
import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.TemporalField;
import java.time.temporal.ValueRange;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import sun.util.logging.PlatformLogger;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_MONTH;
import static java.time.temporal.ChronoField.ALIGNED_WEEK_OF_YEAR;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.DAY_OF_WEEK;
import static java.time.temporal.ChronoField.DAY_OF_YEAR;
import static java.time.temporal.ChronoField.EPOCH_DAY;
import static java.time.temporal.ChronoField.ERA;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;
import static java.time.temporal.ChronoField.YEAR;
import static java.time.temporal.ChronoField.YEAR_OF_ERA;
import static java.time.temporal.ChronoUnit.DAYS;
import static java.time.temporal.ChronoUnit.MONTHS;
import static java.time.temporal.ChronoUnit.WEEKS;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
/**
* An abstract implementation of a calendar system, used to organize and identify dates.
* <p>
* The main date and time API is built on the ISO calendar system.
* The chronology operates behind the scenes to represent the general concept of a calendar system.
* <p>
* See {@link Chronology} for more details.
*
* @implSpec This class is separated from the {@code Chronology} interface so that the static methods
* are not inherited. While {@code Chronology} can be implemented directly, it is strongly
* recommended to extend this abstract class instead.
* <p>
* This class must be implemented with care to ensure other classes operate correctly.
* All implementations that can be instantiated must be final, immutable and thread-safe.
* Subclasses should be Serializable wherever possible.
* @since 1.8
*/
// 历法系统的抽象实现,主要提供了对时间量字段的解析方法
public abstract class AbstractChronology implements Chronology {
/**
* Map of available calendars by ID.
*/
// 缓存注册的历法系统:key的历法的ID,value是历法实例
private static final ConcurrentHashMap<String, Chronology> CHRONOS_BY_ID = new ConcurrentHashMap<>();
/**
* Map of available calendars by calendar type.
*/
// 缓存注册的历法系统:key的历法的类型,value是历法实例
private static final ConcurrentHashMap<String, Chronology> CHRONOS_BY_TYPE = new ConcurrentHashMap<>();
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Creates an instance.
*/
protected AbstractChronology() {
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 工厂方法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Obtains an instance of {@code Chronology} from a chronology ID or
* calendar system type.
* <p>
* See {@link Chronology#of(String)}.
*
* @param idOrType the chronology ID or calendar system type, not null
*
* @return the chronology with the identifier requested, not null
*
* @throws java.time.DateTimeException if the chronology cannot be found
*/
// 根据指定的历法ID或历法类型,(构造并)返回对应的历法系统
static Chronology of(String idOrType) {
Objects.requireNonNull(idOrType, "idOrType");
do {
// 根据指定的历法ID或历法类型,从缓存中获取到注册的历法系统
Chronology chrono = of0(idOrType);
if(chrono != null) {
return chrono;
}
// If not found, do the initialization (once) and repeat the lookup
} while(initCache());
// Look for a Chronology using ServiceLoader of the Thread's ContextClassLoader.
// Application provided Chronologies must not be cached.
@SuppressWarnings("rawtypes")
ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class);
for(Chronology chrono : loader) {
if(idOrType.equals(chrono.getId()) || idOrType.equals(chrono.getCalendarType())) {
return chrono;
}
}
throw new DateTimeException("Unknown chronology: " + idOrType);
}
/**
* Obtains an instance of {@code Chronology} from a locale.
* <p>
* See {@link Chronology#ofLocale(Locale)}.
*
* @param locale the locale to use to obtain the calendar system, not null
*
* @return the calendar system associated with the locale, not null
*
* @throws java.time.DateTimeException if the locale-specified calendar cannot be found
*/
// 返回指定区域可用的历法系统
static Chronology ofLocale(Locale locale) {
Objects.requireNonNull(locale, "locale");
// 获取当前可用的历法类型
String type = locale.getUnicodeLocaleType("ca");
if(type == null || "iso".equals(type) || "iso8601".equals(type)) {
// 默认使用ISO历法
return IsoChronology.INSTANCE;
}
// Not pre-defined; lookup by the type
do {
Chronology chrono = CHRONOS_BY_TYPE.get(type);
if(chrono != null) {
return chrono;
}
// If not found, do the initialization (once) and repeat the lookup
} while(initCache());
// Look for a Chronology using ServiceLoader of the Thread's ContextClassLoader.
// Application provided Chronologies must not be cached.
@SuppressWarnings("rawtypes")
ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class);
for(Chronology chrono : loader) {
if(type.equals(chrono.getCalendarType())) {
return chrono;
}
}
throw new DateTimeException("Unknown calendar system: " + type);
}
/*▲ 工厂方法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 解析时间量字段 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Resolves parsed {@code ChronoField} values into a date during parsing.
* <p>
* Most {@code TemporalField} implementations are resolved using the
* resolve method on the field. By contrast, the {@code ChronoField} class
* defines fields that only have meaning relative to the chronology.
* As such, {@code ChronoField} date fields are resolved here in the
* context of a specific chronology.
* <p>
* {@code ChronoField} instances are resolved by this method, which may
* be overridden in subclasses.
* <ul>
* <li>{@code EPOCH_DAY} - If present, this is converted to a date and
* all other date fields are then cross-checked against the date.
* <li>{@code PROLEPTIC_MONTH} - If present, then it is split into the
* {@code YEAR} and {@code MONTH_OF_YEAR}. If the mode is strict or smart
* then the field is validated.
* <li>{@code YEAR_OF_ERA} and {@code ERA} - If both are present, then they
* are combined to form a {@code YEAR}. In lenient mode, the {@code YEAR_OF_ERA}
* range is not validated, in smart and strict mode it is. The {@code ERA} is
* validated for range in all three modes. If only the {@code YEAR_OF_ERA} is
* present, and the mode is smart or lenient, then the last available era
* is assumed. In strict mode, no era is assumed and the {@code YEAR_OF_ERA} is
* left untouched. If only the {@code ERA} is present, then it is left untouched.
* <li>{@code YEAR}, {@code MONTH_OF_YEAR} and {@code DAY_OF_MONTH} -
* If all three are present, then they are combined to form a date.
* In all three modes, the {@code YEAR} is validated.
* If the mode is smart or strict, then the month and day are validated.
* If the mode is lenient, then the date is combined in a manner equivalent to
* creating a date on the first day of the first month in the requested year,
* then adding the difference in months, then the difference in days.
* If the mode is smart, and the day-of-month is greater than the maximum for
* the year-month, then the day-of-month is adjusted to the last day-of-month.
* If the mode is strict, then the three fields must form a valid date.
* <li>{@code YEAR} and {@code DAY_OF_YEAR} -
* If both are present, then they are combined to form a date.
* In all three modes, the {@code YEAR} is validated.
* If the mode is lenient, then the date is combined in a manner equivalent to
* creating a date on the first day of the requested year, then adding
* the difference in days.
* If the mode is smart or strict, then the two fields must form a valid date.
* <li>{@code YEAR}, {@code MONTH_OF_YEAR}, {@code ALIGNED_WEEK_OF_MONTH} and
* {@code ALIGNED_DAY_OF_WEEK_IN_MONTH} -
* If all four are present, then they are combined to form a date.
* In all three modes, the {@code YEAR} is validated.
* If the mode is lenient, then the date is combined in a manner equivalent to
* creating a date on the first day of the first month in the requested year, then adding
* the difference in months, then the difference in weeks, then in days.
* If the mode is smart or strict, then the all four fields are validated to
* their outer ranges. The date is then combined in a manner equivalent to
* creating a date on the first day of the requested year and month, then adding
* the amount in weeks and days to reach their values. If the mode is strict,
* the date is additionally validated to check that the day and week adjustment
* did not change the month.
* <li>{@code YEAR}, {@code MONTH_OF_YEAR}, {@code ALIGNED_WEEK_OF_MONTH} and
* {@code DAY_OF_WEEK} - If all four are present, then they are combined to
* form a date. The approach is the same as described above for
* years, months and weeks in {@code ALIGNED_DAY_OF_WEEK_IN_MONTH}.
* The day-of-week is adjusted as the next or same matching day-of-week once
* the years, months and weeks have been handled.
* <li>{@code YEAR}, {@code ALIGNED_WEEK_OF_YEAR} and {@code ALIGNED_DAY_OF_WEEK_IN_YEAR} -
* If all three are present, then they are combined to form a date.
* In all three modes, the {@code YEAR} is validated.
* If the mode is lenient, then the date is combined in a manner equivalent to
* creating a date on the first day of the requested year, then adding
* the difference in weeks, then in days.
* If the mode is smart or strict, then the all three fields are validated to
* their outer ranges. The date is then combined in a manner equivalent to
* creating a date on the first day of the requested year, then adding
* the amount in weeks and days to reach their values. If the mode is strict,
* the date is additionally validated to check that the day and week adjustment
* did not change the year.
* <li>{@code YEAR}, {@code ALIGNED_WEEK_OF_YEAR} and {@code DAY_OF_WEEK} -
* If all three are present, then they are combined to form a date.
* The approach is the same as described above for years and weeks in
* {@code ALIGNED_DAY_OF_WEEK_IN_YEAR}. The day-of-week is adjusted as the
* next or same matching day-of-week once the years and weeks have been handled.
* </ul>
* <p>
* The default implementation is suitable for most calendar systems.
* If {@link java.time.temporal.ChronoField#YEAR_OF_ERA} is found without an {@link java.time.temporal.ChronoField#ERA}
* then the last era in {@link #eras()} is used.
* The implementation assumes a 7 day week, that the first day-of-month
* has the value 1, that first day-of-year has the value 1, and that the
* first of the month and year always exists.
*
* @param fieldValues the map of fields to values, which can be updated, not null
* @param resolverStyle the requested type of resolve, not null
*
* @return the resolved date, null if insufficient information to create a date
*
* @throws java.time.DateTimeException if the date cannot be resolved, typically
* because of a conflict in the input data
*/
/*
* 从fieldValues中解析出时间量字段的值,然后用这些值来构造本地日期。
*
* resolverStyle: 指示解析时间量字段的策略
*/
@Override
public ChronoLocalDate resolveDate(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
/* check epoch-day before inventing era */
if(fieldValues.containsKey(EPOCH_DAY)) {
return dateEpochDay(fieldValues.remove(EPOCH_DAY));
}
/* fix proleptic month before inventing era */
// 从fieldValues中解析[Proleptic-月]信息
resolveProlepticMonth(fieldValues, resolverStyle);
/* invent era if necessary to resolve year-of-era */
// 尝试从中解析[iSO年份]信息,并将其转换为[Proleptic年]后存入fieldValues
ChronoLocalDate resolved = resolveYearOfEra(fieldValues, resolverStyle);
if(resolved != null) {
return resolved;
}
// 如果不包含[Proleptic年]信息,则直接返回
if(!fieldValues.containsKey(YEAR)) {
return null;
}
// 解析位于年中的[月]
if(fieldValues.containsKey(MONTH_OF_YEAR)) {
// 解析位于月中的[天]
if(fieldValues.containsKey(DAY_OF_MONTH)) {
return resolveYMD(fieldValues, resolverStyle);
}
// 可以假设当月第一天位于第1周
if(fieldValues.containsKey(ALIGNED_WEEK_OF_MONTH)) {
// 可以假设当月第一天是周一
if(fieldValues.containsKey(ALIGNED_DAY_OF_WEEK_IN_MONTH)) {
return resolveYMAA(fieldValues, resolverStyle);
}
// 解析位于周中的[天],即周几
if(fieldValues.containsKey(DAY_OF_WEEK)) {
return resolveYMAD(fieldValues, resolverStyle);
}
}
}
// 位于年中的[天]
if(fieldValues.containsKey(DAY_OF_YEAR)) {
// 从fieldValues中解析年份和位于年中的[天]
return resolveYD(fieldValues, resolverStyle);
}
// 可以假设当年第一天位于第1周
if(fieldValues.containsKey(ALIGNED_WEEK_OF_YEAR)) {
// 可以假设当年第一天是周一
if(fieldValues.containsKey(ALIGNED_DAY_OF_WEEK_IN_YEAR)) {
return resolveYAA(fieldValues, resolverStyle);
}
// 解析位于周中的[天],即周几
if(fieldValues.containsKey(DAY_OF_WEEK)) {
return resolveYAD(fieldValues, resolverStyle);
}
}
return null;
}
// 从fieldValues中解析[Proleptic-月]信息
void resolveProlepticMonth(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
Long pMonth = fieldValues.remove(PROLEPTIC_MONTH);
if(pMonth == null) {
return;
}
if(resolverStyle != ResolverStyle.LENIENT) {
PROLEPTIC_MONTH.checkValidValue(pMonth);
}
// first day-of-month is likely to be safest for setting proleptic-month
// cannot add to year zero, as not all chronologies have a year zero
ChronoLocalDate chronoDate = dateNow().with(DAY_OF_MONTH, 1).with(PROLEPTIC_MONTH, pMonth);
addFieldValue(fieldValues, MONTH_OF_YEAR, chronoDate.get(MONTH_OF_YEAR));
addFieldValue(fieldValues, YEAR, chronoDate.get(YEAR));
}
// 尝试从中解析[iSO年份]信息,并将其转换为[Proleptic年]后存入fieldValues
ChronoLocalDate resolveYearOfEra(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
// 从fieldValues中获取字段YEAR_OF_ERA的值(ISO年份)
Long yoeLong = fieldValues.remove(YEAR_OF_ERA);
// 如果包含[iSO年份]字段
if(yoeLong != null) {
int yoe;
if(resolverStyle == ResolverStyle.LENIENT) {
yoe = Math.toIntExact(yoeLong);
} else {
yoe = range(YEAR_OF_ERA).checkValidIntValue(yoeLong, YEAR_OF_ERA);
}
// 从fieldValues中获取字段YEAR_OF_ERA的值(纪元)
Long eraLong = fieldValues.remove(ERA);
// 如果包含[纪元]字段,直接使用该[纪元]与[ISO年份]构造为一个"Proleptic年"存入fieldValues
if(eraLong != null) {
Era eraObj = eraOf(range(ERA).checkValidIntValue(eraLong, ERA));
// 将eraObj处的ISO年份(公历年)转换为"Proleptic年"
int prolepticYear = prolepticYear(eraObj, yoe);
addFieldValue(fieldValues, YEAR, prolepticYear);
// 如果不包含[纪元]字段
} else {
// 如果包含[Proleptic年]字段,则尝试使用[Proleptic年]年所在的纪元与[iSO年份]构造为一个新的"Proleptic年"存入fieldValues
if(fieldValues.containsKey(YEAR)) {
int year = range(YEAR).checkValidIntValue(fieldValues.get(YEAR), YEAR);
// 构造一个"本地日期"对象,代表该年份的第一天
ChronoLocalDate chronoDate = dateYearDay(year, 1);
// 返回当前日期所属的纪元
Era era = chronoDate.getEra();
// 将era处的ISO年份(公历年)转换为一个新的"Proleptic年"
int prolepticYear = prolepticYear(era, yoe);
addFieldValue(fieldValues, YEAR, prolepticYear);
// 在严格模式下,再将该[iSO年份]还原到fieldValues中
} else if(resolverStyle == ResolverStyle.STRICT) {
// do not invent era if strict.
// reinstate the field removed earlier, no cross-check issues.
fieldValues.put(YEAR_OF_ERA, yoeLong);
} else {
// 获取当前历法系统下可用的纪元
List<Era> eras = eras();
// 没有可用纪元,则将该[iSO年份]回退为[Proleptic年]
if(eras.isEmpty()) {
addFieldValue(fieldValues, YEAR, yoe);
// 如果存在可以纪元,则默认使用最后一个纪元与[iSO年份]构造一个"Proleptic年"存入fieldValues
} else {
Era eraObj = eras.get(eras.size() - 1);
addFieldValue(fieldValues, YEAR, prolepticYear(eraObj, yoe));
}
}
}
// 不存在[iSO年份]时,尝试解析[纪元]信息,检查其有效性
} else if(fieldValues.containsKey(ERA)) {
range(ERA).checkValidValue(fieldValues.get(ERA), ERA); // always validated
}
return null;
}
// 从fieldValues中解析出年/月/日信息
ChronoLocalDate resolveYMD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if(resolverStyle == ResolverStyle.LENIENT) {
long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);
long days = Math.subtractExact(fieldValues.remove(DAY_OF_MONTH), 1);
return date(y, 1, 1).plus(months, MONTHS).plus(days, DAYS);
}
int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR), MONTH_OF_YEAR);
ValueRange domRange = range(DAY_OF_MONTH);
int dom = domRange.checkValidIntValue(fieldValues.remove(DAY_OF_MONTH), DAY_OF_MONTH);
if(resolverStyle == ResolverStyle.SMART) { // previous valid
try {
return date(y, moy, dom);
} catch(DateTimeException ex) {
return date(y, moy, 1).with(TemporalAdjusters.lastDayOfMonth());
}
}
return date(y, moy, dom);
}
// 从fieldValues中解析年份和位于年中的[天]
ChronoLocalDate resolveYD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if(resolverStyle == ResolverStyle.LENIENT) {
long days = Math.subtractExact(fieldValues.remove(DAY_OF_YEAR), 1);
return dateYearDay(y, 1).plus(days, DAYS);
}
int doy = range(DAY_OF_YEAR).checkValidIntValue(fieldValues.remove(DAY_OF_YEAR), DAY_OF_YEAR);
return dateYearDay(y, doy); // smart is same as strict
}
ChronoLocalDate resolveYMAA(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if(resolverStyle == ResolverStyle.LENIENT) {
long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), 1);
long days = Math.subtractExact(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_MONTH), 1);
return date(y, 1, 1).plus(months, MONTHS).plus(weeks, WEEKS).plus(days, DAYS);
}
int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR), MONTH_OF_YEAR);
int aw = range(ALIGNED_WEEK_OF_MONTH).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), ALIGNED_WEEK_OF_MONTH);
int ad = range(ALIGNED_DAY_OF_WEEK_IN_MONTH).checkValidIntValue(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_MONTH), ALIGNED_DAY_OF_WEEK_IN_MONTH);
ChronoLocalDate date = date(y, moy, 1).plus((aw - 1) * 7 + (ad - 1), DAYS);
if(resolverStyle == ResolverStyle.STRICT && date.get(MONTH_OF_YEAR) != moy) {
throw new DateTimeException("Strict mode rejected resolved date as it is in a different month");
}
return date;
}
ChronoLocalDate resolveYMAD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if(resolverStyle == ResolverStyle.LENIENT) {
long months = Math.subtractExact(fieldValues.remove(MONTH_OF_YEAR), 1);
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), 1);
long dow = Math.subtractExact(fieldValues.remove(DAY_OF_WEEK), 1);
return resolveAligned(date(y, 1, 1), months, weeks, dow);
}
int moy = range(MONTH_OF_YEAR).checkValidIntValue(fieldValues.remove(MONTH_OF_YEAR), MONTH_OF_YEAR);
int aw = range(ALIGNED_WEEK_OF_MONTH).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_MONTH), ALIGNED_WEEK_OF_MONTH);
int dow = range(DAY_OF_WEEK).checkValidIntValue(fieldValues.remove(DAY_OF_WEEK), DAY_OF_WEEK);
ChronoLocalDate date = date(y, moy, 1).plus((aw - 1) * 7, DAYS).with(nextOrSame(DayOfWeek.of(dow)));
if(resolverStyle == ResolverStyle.STRICT && date.get(MONTH_OF_YEAR) != moy) {
throw new DateTimeException("Strict mode rejected resolved date as it is in a different month");
}
return date;
}
ChronoLocalDate resolveYAA(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if(resolverStyle == ResolverStyle.LENIENT) {
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), 1);
long days = Math.subtractExact(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_YEAR), 1);
return dateYearDay(y, 1).plus(weeks, WEEKS).plus(days, DAYS);
}
int aw = range(ALIGNED_WEEK_OF_YEAR).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), ALIGNED_WEEK_OF_YEAR);
int ad = range(ALIGNED_DAY_OF_WEEK_IN_YEAR).checkValidIntValue(fieldValues.remove(ALIGNED_DAY_OF_WEEK_IN_YEAR), ALIGNED_DAY_OF_WEEK_IN_YEAR);
ChronoLocalDate date = dateYearDay(y, 1).plus((aw - 1) * 7 + (ad - 1), DAYS);
if(resolverStyle == ResolverStyle.STRICT && date.get(YEAR) != y) {
throw new DateTimeException("Strict mode rejected resolved date as it is in a different year");
}
return date;
}
ChronoLocalDate resolveYAD(Map<TemporalField, Long> fieldValues, ResolverStyle resolverStyle) {
int y = range(YEAR).checkValidIntValue(fieldValues.remove(YEAR), YEAR);
if(resolverStyle == ResolverStyle.LENIENT) {
long weeks = Math.subtractExact(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), 1);
long dow = Math.subtractExact(fieldValues.remove(DAY_OF_WEEK), 1);
return resolveAligned(dateYearDay(y, 1), 0, weeks, dow);
}
int aw = range(ALIGNED_WEEK_OF_YEAR).checkValidIntValue(fieldValues.remove(ALIGNED_WEEK_OF_YEAR), ALIGNED_WEEK_OF_YEAR);
int dow = range(DAY_OF_WEEK).checkValidIntValue(fieldValues.remove(DAY_OF_WEEK), DAY_OF_WEEK);
ChronoLocalDate date = dateYearDay(y, 1).plus((aw - 1) * 7, DAYS).with(nextOrSame(DayOfWeek.of(dow)));
if(resolverStyle == ResolverStyle.STRICT && date.get(YEAR) != y) {
throw new DateTimeException("Strict mode rejected resolved date as it is in a different year");
}
return date;
}
ChronoLocalDate resolveAligned(ChronoLocalDate base, long months, long weeks, long dow) {
ChronoLocalDate date = base.plus(months, MONTHS).plus(weeks, WEEKS);
if(dow>7) {
date = date.plus((dow - 1) / 7, WEEKS);
dow = ((dow - 1) % 7) + 1;
} else if(dow<1) {
date = date.plus(Math.subtractExact(dow, 7) / 7, WEEKS);
dow = ((dow + 6) % 7) + 1;
}
return date.with(nextOrSame(DayOfWeek.of((int) dow)));
}
/**
* Adds a field-value pair to the map, checking for conflicts.
* <p>
* If the field is not already present, then the field-value pair is added to the map.
* If the field is already present and it has the same value as that specified, no action occurs.
* If the field is already present and it has a different value to that specified, then
* an exception is thrown.
*
* @param field the field to add, not null
* @param value the value to add, not null
*
* @throws java.time.DateTimeException if the field is already present with a different value
*/
// 向fieldValues中存入键值对<field, value>
void addFieldValue(Map<TemporalField, Long> fieldValues, ChronoField field, long value) {
Long old = fieldValues.get(field); // check first for better error message
if(old != null && old != value) {
throw new DateTimeException("Conflict found: " + field + " " + old + " differs from " + field + " " + value);
}
fieldValues.put(field, value);
}
/*▲ 解析时间量字段 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 注册/获取历法系统 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the available chronologies.
* <p>
* Each returned {@code Chronology} is available for use in the system.
* The set of chronologies includes the system chronologies and
* any chronologies provided by the application via ServiceLoader
* configuration.
*
* @return the independent, modifiable set of the available chronology IDs, not null
*/
// 返回当前可用的历法系统,包括自定义的历法系统
static Set<Chronology> getAvailableChronologies() {
initCache(); // force initialization
HashSet<Chronology> chronos = new HashSet<>(CHRONOS_BY_ID.values());
/// Add in Chronologies from the ServiceLoader configuration
@SuppressWarnings("rawtypes")
ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class);
for(Chronology chrono : loader) {
chronos.add(chrono);
}
return chronos;
}
/**
* Initialization of the maps from id and type to Chronology.
* The ServiceLoader is used to find and register any implementations
* of {@link java.time.chrono.AbstractChronology} found in the bootclass loader.
* The built-in chronologies are registered explicitly.
* Calendars configured via the Thread's context classloader are local
* to that thread and are ignored.
* <p>
* The initialization is done only once using the registration
* of the IsoChronology as the test and the final step.
* Multiple threads may perform the initialization concurrently.
* Only the first registration of each Chronology is retained by the
* ConcurrentHashMap.
*
* @return true if the cache was initialized
*/
// 注册指定的历法系统
private static boolean initCache() {
if(CHRONOS_BY_ID.get("ISO") != null) {
return false;
}
// Initialization is incomplete
// Register built-in Chronologies
registerChrono(HijrahChronology.INSTANCE);
registerChrono(JapaneseChronology.INSTANCE);
registerChrono(MinguoChronology.INSTANCE);
registerChrono(ThaiBuddhistChronology.INSTANCE);
// Register Chronologies from the ServiceLoader
@SuppressWarnings("rawtypes")
ServiceLoader<AbstractChronology> loader = ServiceLoader.load(AbstractChronology.class, null);
for(AbstractChronology chrono : loader) {
String id = chrono.getId();
if(id.equals("ISO") || registerChrono(chrono) != null) {
// Log the attempt to replace an existing Chronology
PlatformLogger logger = PlatformLogger.getLogger("java.time.chrono");
logger.warning("Ignoring duplicate Chronology, from ServiceLoader configuration " + id);
}
}
// finally, register IsoChronology to mark initialization is complete
registerChrono(IsoChronology.INSTANCE);
return true;
}
/**
* Register a Chronology by its ID and type for lookup by {@link #of(String)}.
* Chronologies must not be registered until they are completely constructed.
* Specifically, not in the constructor of Chronology.
*
* @param chrono the chronology to register; not null
*
* @return the already registered Chronology if any, may be null
*/
// 注册指定的历法系统
static Chronology registerChrono(Chronology chrono) {
return registerChrono(chrono, chrono.getId());
}
/**
* Register a Chronology by ID and type for lookup by {@link #of(String)}.
* Chronos must not be registered until they are completely constructed.
* Specifically, not in the constructor of Chronology.
*
* @param chrono the chronology to register; not null
* @param id the ID to register the chronology; not null
*
* @return the already registered Chronology if any, may be null
*/
// 注册指定的历法系统
static Chronology registerChrono(Chronology chrono, String id) {
Chronology prev = CHRONOS_BY_ID.putIfAbsent(id, chrono);
if(prev == null) {
// 获取历法系统的类型
String type = chrono.getCalendarType();
if(type != null) {
CHRONOS_BY_TYPE.putIfAbsent(type, chrono);
}
}
return prev;
}
/**
* Obtains an instance of {@code Chronology} from a chronology ID or
* calendar system type.
*
* @param id the chronology ID or calendar system type, not null
*
* @return the chronology with the identifier requested, or {@code null} if not found
*/
// 根据指定的历法ID或历法类型,从缓存中获取到注册的历法系统
private static Chronology of0(String idOrType) {
Chronology chrono = CHRONOS_BY_ID.get(idOrType);
if(chrono == null) {
chrono = CHRONOS_BY_TYPE.get(idOrType);
}
return chrono;
}
/*▲ 注册/获取历法系统 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 序列化 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Defend against malicious streams.
*
* @param s the stream to read
*
* @throws java.io.InvalidObjectException always
*/
private void readObject(ObjectInputStream s) throws ObjectStreamException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
/**
* Writes the Chronology using a
* <a href="../../../serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.
* <pre>
* out.writeByte(1); // identifies this as a Chronology
* out.writeUTF(getId());
* </pre>
*
* @return the instance of {@code Ser}, not null
*/
Object writeReplace() {
return new Ser(Ser.CHRONO_TYPE, this);
}
static Chronology readExternal(DataInput in) throws IOException {
String id = in.readUTF();
return Chronology.of(id);
}
void writeExternal(DataOutput out) throws IOException {
out.writeUTF(getId());
}
/*▲ 序列化 ████████████████████████████████████████████████████████████████████████████████┛ */
/**
* Compares this chronology to another chronology.
* <p>
* The comparison order first by the chronology ID string, then by any
* additional information specific to the subclass.
* It is "consistent with equals", as defined by {@link Comparable}.
*
* @param other the other chronology to compare to, not null
*
* @return the comparator value, negative if less, positive if greater
*
* @implSpec This implementation compares the chronology ID.
* Subclasses must compare any additional state that they store.
*/
@Override
public int compareTo(Chronology other) {
return getId().compareTo(other.getId());
}
/**
* Outputs this chronology as a {@code String}, using the chronology ID.
*
* @return a string representation of this chronology, not null
*/
@Override
public String toString() {
return getId();
}
/**
* Checks if this chronology is equal to another chronology.
* <p>
* The comparison is based on the entire state of the object.
*
* @param obj the object to check, null returns false
*
* @return true if this is equal to the other chronology
*
* @implSpec This implementation checks the type and calls
* {@link #compareTo(java.time.chrono.Chronology)}.
*/
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj instanceof AbstractChronology) {
return compareTo((AbstractChronology) obj) == 0;
}
return false;
}
/**
* A hash code for this chronology.
* <p>
* The hash code should be based on the entire state of the object.
*
* @return a suitable hash code
*
* @implSpec This implementation is based on the chronology ID and class.
* Subclasses should add any additional state that they store.
*/
@Override
public int hashCode() {
return getClass().hashCode() ^ getId().hashCode();
}
}