Path: blob/master/src/java.base/share/classes/java/lang/Enum.java
41152 views
/*1* Copyright (c) 2003, 2020, 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*/2425package java.lang;2627import java.io.IOException;28import java.io.InvalidObjectException;29import java.io.ObjectInputStream;30import java.io.ObjectStreamException;31import java.io.Serializable;32import java.lang.constant.ClassDesc;33import java.lang.constant.Constable;34import java.lang.constant.ConstantDescs;35import java.lang.constant.DynamicConstantDesc;36import java.lang.invoke.MethodHandles;37import java.util.Optional;3839import static java.util.Objects.requireNonNull;4041/**42* This is the common base class of all Java language enumeration classes.43*44* More information about enums, including descriptions of the45* implicitly declared methods synthesized by the compiler, can be46* found in section {@jls 8.9} of <cite>The Java Language47* Specification</cite>.48*49* Enumeration classes are all serializable and receive special handling50* by the serialization mechanism. The serialized representation used51* for enum constants cannot be customized. Declarations of methods52* and fields that would otherwise interact with serialization are53* ignored, including {@code serialVersionUID}; see the <cite>Java54* Object Serialization Specification</cite> for details.55*56* <p> Note that when using an enumeration type as the type of a set57* or as the type of the keys in a map, specialized and efficient58* {@linkplain java.util.EnumSet set} and {@linkplain59* java.util.EnumMap map} implementations are available.60*61* @param <E> The type of the enum subclass62* @serial exclude63* @author Josh Bloch64* @author Neal Gafter65* @see Class#getEnumConstants()66* @see java.util.EnumSet67* @see java.util.EnumMap68* @jls 8.9 Enum Classes69* @jls 8.9.3 Enum Members70* @since 1.571*/72@SuppressWarnings("serial") // No serialVersionUID needed due to73// special-casing of enum classes.74public abstract class Enum<E extends Enum<E>>75implements Constable, Comparable<E>, Serializable {76/**77* The name of this enum constant, as declared in the enum declaration.78* Most programmers should use the {@link #toString} method rather than79* accessing this field.80*/81private final String name;8283/**84* Returns the name of this enum constant, exactly as declared in its85* enum declaration.86*87* <b>Most programmers should use the {@link #toString} method in88* preference to this one, as the toString method may return89* a more user-friendly name.</b> This method is designed primarily for90* use in specialized situations where correctness depends on getting the91* exact name, which will not vary from release to release.92*93* @return the name of this enum constant94*/95public final String name() {96return name;97}9899/**100* The ordinal of this enumeration constant (its position101* in the enum declaration, where the initial constant is assigned102* an ordinal of zero).103*104* Most programmers will have no use for this field. It is designed105* for use by sophisticated enum-based data structures, such as106* {@link java.util.EnumSet} and {@link java.util.EnumMap}.107*/108private final int ordinal;109110/**111* Returns the ordinal of this enumeration constant (its position112* in its enum declaration, where the initial constant is assigned113* an ordinal of zero).114*115* Most programmers will have no use for this method. It is116* designed for use by sophisticated enum-based data structures, such117* as {@link java.util.EnumSet} and {@link java.util.EnumMap}.118*119* @return the ordinal of this enumeration constant120*/121public final int ordinal() {122return ordinal;123}124125/**126* Sole constructor. Programmers cannot invoke this constructor.127* It is for use by code emitted by the compiler in response to128* enum class declarations.129*130* @param name - The name of this enum constant, which is the identifier131* used to declare it.132* @param ordinal - The ordinal of this enumeration constant (its position133* in the enum declaration, where the initial constant is assigned134* an ordinal of zero).135*/136protected Enum(String name, int ordinal) {137this.name = name;138this.ordinal = ordinal;139}140141/**142* Returns the name of this enum constant, as contained in the143* declaration. This method may be overridden, though it typically144* isn't necessary or desirable. An enum class should override this145* method when a more "programmer-friendly" string form exists.146*147* @return the name of this enum constant148*/149public String toString() {150return name;151}152153/**154* Returns true if the specified object is equal to this155* enum constant.156*157* @param other the object to be compared for equality with this object.158* @return true if the specified object is equal to this159* enum constant.160*/161public final boolean equals(Object other) {162return this==other;163}164165/**166* Returns a hash code for this enum constant.167*168* @return a hash code for this enum constant.169*/170public final int hashCode() {171return super.hashCode();172}173174/**175* Throws CloneNotSupportedException. This guarantees that enums176* are never cloned, which is necessary to preserve their "singleton"177* status.178*179* @return (never returns)180*/181protected final Object clone() throws CloneNotSupportedException {182throw new CloneNotSupportedException();183}184185/**186* Compares this enum with the specified object for order. Returns a187* negative integer, zero, or a positive integer as this object is less188* than, equal to, or greater than the specified object.189*190* Enum constants are only comparable to other enum constants of the191* same enum type. The natural order implemented by this192* method is the order in which the constants are declared.193*/194public final int compareTo(E o) {195Enum<?> other = (Enum<?>)o;196Enum<E> self = this;197if (self.getClass() != other.getClass() && // optimization198self.getDeclaringClass() != other.getDeclaringClass())199throw new ClassCastException();200return self.ordinal - other.ordinal;201}202203/**204* Returns the Class object corresponding to this enum constant's205* enum type. Two enum constants e1 and e2 are of the206* same enum type if and only if207* e1.getDeclaringClass() == e2.getDeclaringClass().208* (The value returned by this method may differ from the one returned209* by the {@link Object#getClass} method for enum constants with210* constant-specific class bodies.)211*212* @return the Class object corresponding to this enum constant's213* enum type214*/215@SuppressWarnings("unchecked")216public final Class<E> getDeclaringClass() {217Class<?> clazz = getClass();218Class<?> zuper = clazz.getSuperclass();219return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;220}221222/**223* Returns an enum descriptor {@code EnumDesc} for this instance, if one can be224* constructed, or an empty {@link Optional} if one cannot be.225*226* @return An {@link Optional} containing the resulting nominal descriptor,227* or an empty {@link Optional} if one cannot be constructed.228* @since 12229*/230@Override231public final Optional<EnumDesc<E>> describeConstable() {232return getDeclaringClass()233.describeConstable()234.map(c -> EnumDesc.of(c, name));235}236237/**238* Returns the enum constant of the specified enum class with the239* specified name. The name must match exactly an identifier used240* to declare an enum constant in this class. (Extraneous whitespace241* characters are not permitted.)242*243* <p>Note that for a particular enum class {@code T}, the244* implicitly declared {@code public static T valueOf(String)}245* method on that enum may be used instead of this method to map246* from a name to the corresponding enum constant. All the247* constants of an enum class can be obtained by calling the248* implicit {@code public static T[] values()} method of that249* class.250*251* @param <T> The enum class whose constant is to be returned252* @param enumClass the {@code Class} object of the enum class from which253* to return a constant254* @param name the name of the constant to return255* @return the enum constant of the specified enum class with the256* specified name257* @throws IllegalArgumentException if the specified enum class has258* no constant with the specified name, or the specified259* class object does not represent an enum class260* @throws NullPointerException if {@code enumClass} or {@code name}261* is null262* @since 1.5263*/264public static <T extends Enum<T>> T valueOf(Class<T> enumClass,265String name) {266T result = enumClass.enumConstantDirectory().get(name);267if (result != null)268return result;269if (name == null)270throw new NullPointerException("Name is null");271throw new IllegalArgumentException(272"No enum constant " + enumClass.getCanonicalName() + "." + name);273}274275/**276* enum classes cannot have finalize methods.277*/278@SuppressWarnings("deprecation")279protected final void finalize() { }280281/**282* prevent default deserialization283*/284@java.io.Serial285private void readObject(ObjectInputStream in) throws IOException,286ClassNotFoundException {287throw new InvalidObjectException("can't deserialize enum");288}289290@java.io.Serial291private void readObjectNoData() throws ObjectStreamException {292throw new InvalidObjectException("can't deserialize enum");293}294295/**296* A <a href="{@docRoot}/java.base/java/lang/constant/package-summary.html#nominal">nominal descriptor</a> for an297* {@code enum} constant.298*299* @param <E> the type of the enum constant300*301* @since 12302*/303public static final class EnumDesc<E extends Enum<E>>304extends DynamicConstantDesc<E> {305306/**307* Constructs a nominal descriptor for the specified {@code enum} class and name.308*309* @param constantClass a {@link ClassDesc} describing the {@code enum} class310* @param constantName the unqualified name of the enum constant311* @throws NullPointerException if any argument is null312* @jvms 4.2.2 Unqualified Names313*/314private EnumDesc(ClassDesc constantClass, String constantName) {315super(ConstantDescs.BSM_ENUM_CONSTANT, requireNonNull(constantName), requireNonNull(constantClass));316}317318/**319* Returns a nominal descriptor for the specified {@code enum} class and name320*321* @param <E> the type of the enum constant322* @param enumClass a {@link ClassDesc} describing the {@code enum} class323* @param constantName the unqualified name of the enum constant324* @return the nominal descriptor325* @throws NullPointerException if any argument is null326* @jvms 4.2.2 Unqualified Names327* @since 12328*/329public static<E extends Enum<E>> EnumDesc<E> of(ClassDesc enumClass,330String constantName) {331return new EnumDesc<>(enumClass, constantName);332}333334@Override335@SuppressWarnings("unchecked")336public E resolveConstantDesc(MethodHandles.Lookup lookup)337throws ReflectiveOperationException {338return Enum.valueOf((Class<E>) constantType().resolveConstantDesc(lookup), constantName());339}340341@Override342public String toString() {343return String.format("EnumDesc[%s.%s]", constantType().displayName(), constantName());344}345}346}347348349