Path: blob/master/src/java.base/share/classes/java/time/chrono/JapaneseEra.java
41159 views
/*1* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time.chrono;6263import static java.time.chrono.JapaneseDate.MEIJI_6_ISODATE;64import static java.time.temporal.ChronoField.ERA;6566import java.io.DataInput;67import java.io.DataOutput;68import java.io.IOException;69import java.io.InvalidObjectException;70import java.io.ObjectInputStream;71import java.io.ObjectStreamException;72import java.io.Serializable;73import java.time.DateTimeException;74import java.time.LocalDate;75import java.time.format.DateTimeFormatterBuilder;76import java.time.format.TextStyle;77import java.time.temporal.ChronoField;78import java.time.temporal.TemporalField;79import java.time.temporal.UnsupportedTemporalTypeException;80import java.time.temporal.ValueRange;81import java.util.Arrays;82import java.util.Locale;83import java.util.Objects;8485import sun.util.calendar.CalendarDate;8687/**88* An era in the Japanese Imperial calendar system.89* <p>90* The Japanese government defines the official name and start date of91* each era. Eras are consecutive and their date ranges do not overlap,92* so the end date of one era is always the day before the start date93* of the next era.94* <p>95* The Java SE Platform supports all eras defined by the Japanese government,96* beginning with the Meiji era. Each era is identified in the Platform by an97* integer value and a name. The {@link #of(int)} and {@link #valueOf(String)}98* methods may be used to obtain a singleton instance of {@code JapaneseEra}99* for each era. The {@link #values()} method returns the singleton instances100* of all supported eras.101* <p>102* For convenience, this class declares a number of public static final fields103* that refer to singleton instances returned by the {@link #values()} method.104*105* @apiNote106* The fields declared in this class may evolve over time, in line with the107* results of the {@link #values()} method. However, there is not necessarily108* a 1:1 correspondence between the fields and the singleton instances.109*110* @apiNote111* The Japanese government may announce a new era and define its start112* date but not its official name. In this scenario, the singleton instance113* that represents the new era may return a name that is not stable until114* the official name is defined. Developers should exercise caution when115* relying on the name returned by any singleton instance that does not116* correspond to a public static final field.117*118* @implSpec119* This class is immutable and thread-safe.120*121* @since 1.8122*/123public final class JapaneseEra124implements Era, Serializable {125126// The offset value to 0-based index from the era value.127// i.e., getValue() + ERA_OFFSET == 0-based index128static final int ERA_OFFSET = 2;129130static final sun.util.calendar.Era[] ERA_CONFIG;131132/**133* The singleton instance for the 'Meiji' era (1868-01-01 - 1912-07-29)134* which has the value -1.135*/136public static final JapaneseEra MEIJI = new JapaneseEra(-1, LocalDate.of(1868, 1, 1));137/**138* The singleton instance for the 'Taisho' era (1912-07-30 - 1926-12-24)139* which has the value 0.140*/141public static final JapaneseEra TAISHO = new JapaneseEra(0, LocalDate.of(1912, 7, 30));142/**143* The singleton instance for the 'Showa' era (1926-12-25 - 1989-01-07)144* which has the value 1.145*/146public static final JapaneseEra SHOWA = new JapaneseEra(1, LocalDate.of(1926, 12, 25));147/**148* The singleton instance for the 'Heisei' era (1989-01-08 - 2019-04-30)149* which has the value 2.150*/151public static final JapaneseEra HEISEI = new JapaneseEra(2, LocalDate.of(1989, 1, 8));152/**153* The singleton instance for the 'Reiwa' era (2019-05-01 - )154* which has the value 3. The end date of this era is not specified, unless155* the Japanese Government defines it.156*157* @since 13158*/159public static final JapaneseEra REIWA = new JapaneseEra(3, LocalDate.of(2019, 5, 1));160161// The number of predefined JapaneseEra constants.162// There may be a supplemental era defined by the property.163private static final int N_ERA_CONSTANTS = REIWA.getValue() + ERA_OFFSET;164165/**166* Serialization version.167*/168@java.io.Serial169private static final long serialVersionUID = 1466499369062886794L;170171// array for the singleton JapaneseEra instances172private static final JapaneseEra[] KNOWN_ERAS;173174static {175ERA_CONFIG = JapaneseChronology.JCAL.getEras();176177KNOWN_ERAS = new JapaneseEra[ERA_CONFIG.length];178KNOWN_ERAS[0] = MEIJI;179KNOWN_ERAS[1] = TAISHO;180KNOWN_ERAS[2] = SHOWA;181KNOWN_ERAS[3] = HEISEI;182KNOWN_ERAS[4] = REIWA;183for (int i = N_ERA_CONSTANTS; i < ERA_CONFIG.length; i++) {184CalendarDate date = ERA_CONFIG[i].getSinceDate();185LocalDate isoDate = LocalDate.of(date.getYear(), date.getMonth(), date.getDayOfMonth());186KNOWN_ERAS[i] = new JapaneseEra(i - ERA_OFFSET + 1, isoDate);187}188};189190/**191* The era value.192* @serial193*/194private final transient int eraValue;195196// the first day of the era197private final transient LocalDate since;198199/**200* Creates an instance.201*202* @param eraValue the era value, validated203* @param since the date representing the first date of the era, validated not null204*/205private JapaneseEra(int eraValue, LocalDate since) {206this.eraValue = eraValue;207this.since = since;208}209210//-----------------------------------------------------------------------211/**212* Returns the Sun private Era instance corresponding to this {@code JapaneseEra}.213*214* @return the Sun private Era instance for this {@code JapaneseEra}.215*/216sun.util.calendar.Era getPrivateEra() {217return ERA_CONFIG[ordinal(eraValue)];218}219220//-----------------------------------------------------------------------221/**222* Obtains an instance of {@code JapaneseEra} from an {@code int} value.223* <ul>224* <li>The value {@code 1} is associated with the 'Showa' era, because225* it contains 1970-01-01 (ISO calendar system).</li>226* <li>The values {@code -1} and {@code 0} are associated with two earlier227* eras, Meiji and Taisho, respectively.</li>228* <li>A value greater than {@code 1} is associated with a later era,229* beginning with Heisei ({@code 2}).</li>230* </ul>231* <p>232* Every instance of {@code JapaneseEra} that is returned from the {@link #values()}233* method has an int value (available via {@link Era#getValue()} which is234* accepted by this method.235*236* @param japaneseEra the era to represent237* @return the {@code JapaneseEra} singleton, not null238* @throws DateTimeException if the value is invalid239*/240public static JapaneseEra of(int japaneseEra) {241int i = ordinal(japaneseEra);242if (i < 0 || i >= KNOWN_ERAS.length) {243throw new DateTimeException("Invalid era: " + japaneseEra);244}245return KNOWN_ERAS[i];246}247248/**249* Returns the {@code JapaneseEra} with the name.250* <p>251* The string must match exactly the name of the era.252* (Extraneous whitespace characters are not permitted.)253* <p>254* Valid era names are the names of eras returned from {@link #values()}.255*256* @param japaneseEra the japaneseEra name; non-null257* @return the {@code JapaneseEra} singleton, never null258* @throws IllegalArgumentException if there is not JapaneseEra with the specified name259*/260public static JapaneseEra valueOf(String japaneseEra) {261Objects.requireNonNull(japaneseEra, "japaneseEra");262for (JapaneseEra era : KNOWN_ERAS) {263if (era.getName().equals(japaneseEra)) {264return era;265}266}267throw new IllegalArgumentException("japaneseEra is invalid");268}269270/**271* Returns an array of JapaneseEras. The array may contain eras defined272* by the Japanese government beyond the known era singletons.273*274* <p>275* This method may be used to iterate over the JapaneseEras as follows:276* <pre>277* for (JapaneseEra c : JapaneseEra.values())278* System.out.println(c);279* </pre>280*281* @return an array of JapaneseEras282*/283public static JapaneseEra[] values() {284return Arrays.copyOf(KNOWN_ERAS, KNOWN_ERAS.length);285}286287/**288* {@inheritDoc}289*290* @param style {@inheritDoc}291* @param locale {@inheritDoc}292*/293@Override294public String getDisplayName(TextStyle style, Locale locale) {295// If this JapaneseEra is a supplemental one, obtain the name from296// the era definition.297if (getValue() > N_ERA_CONSTANTS - ERA_OFFSET) {298Objects.requireNonNull(locale, "locale");299return style.asNormal() == TextStyle.NARROW ? getAbbreviation() : getName();300}301302return new DateTimeFormatterBuilder()303.appendText(ERA, style)304.toFormatter(locale)305.withChronology(JapaneseChronology.INSTANCE)306.format(this == MEIJI ? MEIJI_6_ISODATE : since);307}308309//-----------------------------------------------------------------------310/**311* Obtains an instance of {@code JapaneseEra} from a date.312*313* @param date the date, not null314* @return the Era singleton, never null315*/316static JapaneseEra from(LocalDate date) {317if (date.isBefore(MEIJI_6_ISODATE)) {318throw new DateTimeException("JapaneseDate before Meiji 6 are not supported");319}320for (int i = KNOWN_ERAS.length - 1; i > 0; i--) {321JapaneseEra era = KNOWN_ERAS[i];322if (date.compareTo(era.since) >= 0) {323return era;324}325}326return null;327}328329static JapaneseEra toJapaneseEra(sun.util.calendar.Era privateEra) {330for (int i = ERA_CONFIG.length - 1; i >= 0; i--) {331if (ERA_CONFIG[i].equals(privateEra)) {332return KNOWN_ERAS[i];333}334}335return null;336}337338static sun.util.calendar.Era privateEraFrom(LocalDate isoDate) {339for (int i = KNOWN_ERAS.length - 1; i > 0; i--) {340JapaneseEra era = KNOWN_ERAS[i];341if (isoDate.compareTo(era.since) >= 0) {342return ERA_CONFIG[i];343}344}345return null;346}347348/**349* Returns the index into the arrays from the Era value.350* the eraValue is a valid Era number, -1..2.351*352* @param eraValue the era value to convert to the index353* @return the index of the current Era354*/355private static int ordinal(int eraValue) {356return eraValue + ERA_OFFSET - 1;357}358359//-----------------------------------------------------------------------360/**361* Gets the numeric era {@code int} value.362* <p>363* The {@link #SHOWA} era that contains 1970-01-01 (ISO calendar system) has the value 1.364* Later eras are numbered from 2 ({@link #HEISEI}).365* Earlier eras are numbered 0 ({@link #TAISHO}), -1 ({@link #MEIJI})).366*367* @return the era value368*/369@Override370public int getValue() {371return eraValue;372}373374//-----------------------------------------------------------------------375/**376* Gets the range of valid values for the specified field.377* <p>378* The range object expresses the minimum and maximum valid values for a field.379* This era is used to enhance the accuracy of the returned range.380* If it is not possible to return the range, because the field is not supported381* or for some other reason, an exception is thrown.382* <p>383* If the field is a {@link ChronoField} then the query is implemented here.384* The {@code ERA} field returns the range.385* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.386* <p>387* If the field is not a {@code ChronoField}, then the result of this method388* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}389* passing {@code this} as the argument.390* Whether the range can be obtained is determined by the field.391* <p>392* The range of valid Japanese eras can change over time due to the nature393* of the Japanese calendar system.394*395* @param field the field to query the range for, not null396* @return the range of valid values for the field, not null397* @throws DateTimeException if the range for the field cannot be obtained398* @throws UnsupportedTemporalTypeException if the unit is not supported399*/400@Override // override as super would return range from 0 to 1401public ValueRange range(TemporalField field) {402if (field == ERA) {403return JapaneseChronology.INSTANCE.range(ERA);404}405return Era.super.range(field);406}407408//-----------------------------------------------------------------------409String getAbbreviation() {410return ERA_CONFIG[ordinal(getValue())].getAbbreviation();411}412413String getName() {414return ERA_CONFIG[ordinal(getValue())].getName();415}416417@Override418public String toString() {419return getName();420}421422//-----------------------------------------------------------------------423/**424* Defend against malicious streams.425*426* @param s the stream to read427* @throws InvalidObjectException always428*/429@java.io.Serial430private void readObject(ObjectInputStream s) throws InvalidObjectException {431throw new InvalidObjectException("Deserialization via serialization delegate");432}433434//-----------------------------------------------------------------------435/**436* Writes the object using a437* <a href="{@docRoot}/serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.438* @serialData439* <pre>440* out.writeByte(5); // identifies a JapaneseEra441* out.writeInt(getValue());442* </pre>443*444* @return the instance of {@code Ser}, not null445*/446@java.io.Serial447private Object writeReplace() {448return new Ser(Ser.JAPANESE_ERA_TYPE, this);449}450451void writeExternal(DataOutput out) throws IOException {452out.writeByte(this.getValue());453}454455static JapaneseEra readExternal(DataInput in) throws IOException {456byte eraValue = in.readByte();457return JapaneseEra.of(eraValue);458}459460}461462463