1 /*
   2  * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.io.Serializable;
  29 import java.io.IOException;
  30 import java.io.InvalidObjectException;
  31 import java.io.ObjectInputStream;
  32 import java.io.ObjectStreamException;
  33 
  34 /**
  35  * This is the common base class of all Java language enumeration types.
  36  *
  37  * More information about enums, including descriptions of the
  38  * implicitly declared methods synthesized by the compiler, can be
  39  * found in section 8.9 of
  40  * <cite>The Java&trade; Language Specification</cite>.
  41  *
  42  * <p> Note that when using an enumeration type as the type of a set
  43  * or as the type of the keys in a map, specialized and efficient
  44  * {@linkplain java.util.EnumSet set} and {@linkplain
  45  * java.util.EnumMap map} implementations are available.
  46  *
  47  * @param <E> The enum type subclass
  48  * @serial exclude
  49  * @author  Josh Bloch
  50  * @author  Neal Gafter
  51  * @see     Class#getEnumConstants()
  52  * @see     java.util.EnumSet
  53  * @see     java.util.EnumMap
  54  * @since   1.5
  55  */
  56 @SuppressWarnings("serial") // No serialVersionUID needed due to
  57                             // special-casing of enum types.
  58 public abstract class Enum<E extends Enum<E>>
  59         implements Comparable<E>, Serializable {
  60     /**
  61      * The name of this enum constant, as declared in the enum declaration.
  62      * Most programmers should use the {@link #toString} method rather than
  63      * accessing this field.
  64      */
  65     private final String name;
  66 
  67     /**
  68      * Returns the name of this enum constant, exactly as declared in its
  69      * enum declaration.
  70      *
  71      * <b>Most programmers should use the {@link #toString} method in
  72      * preference to this one, as the toString method may return
  73      * a more user-friendly name.</b>  This method is designed primarily for
  74      * use in specialized situations where correctness depends on getting the
  75      * exact name, which will not vary from release to release.
  76      *
  77      * @return the name of this enum constant
  78      */
  79     public final String name() {
  80         return name;
  81     }
  82 
  83     /**
  84      * The ordinal of this enumeration constant (its position
  85      * in the enum declaration, where the initial constant is assigned
  86      * an ordinal of zero).
  87      *
  88      * Most programmers will have no use for this field.  It is designed
  89      * for use by sophisticated enum-based data structures, such as
  90      * {@link java.util.EnumSet} and {@link java.util.EnumMap}.
  91      */
  92     private final int ordinal;
  93 
  94     /**
  95      * Returns the ordinal of this enumeration constant (its position
  96      * in its enum declaration, where the initial constant is assigned
  97      * an ordinal of zero).
  98      *
  99      * Most programmers will have no use for this method.  It is
 100      * designed for use by sophisticated enum-based data structures, such
 101      * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
 102      *
 103      * @return the ordinal of this enumeration constant
 104      */
 105     public final int ordinal() {
 106         return ordinal;
 107     }
 108 
 109     /**
 110      * Sole constructor.  Programmers cannot invoke this constructor.
 111      * It is for use by code emitted by the compiler in response to
 112      * enum type declarations.
 113      *
 114      * @param name - The name of this enum constant, which is the identifier
 115      *               used to declare it.
 116      * @param ordinal - The ordinal of this enumeration constant (its position
 117      *         in the enum declaration, where the initial constant is assigned
 118      *         an ordinal of zero).
 119      */
 120     protected Enum(String name, int ordinal) {
 121         this.name = name;
 122         this.ordinal = ordinal;
 123     }
 124 
 125     /**
 126      * Returns the name of this enum constant, as contained in the
 127      * declaration.  This method may be overridden, though it typically
 128      * isn't necessary or desirable.  An enum type should override this
 129      * method when a more "programmer-friendly" string form exists.
 130      *
 131      * @return the name of this enum constant
 132      */
 133     public String toString() {
 134         return name;
 135     }
 136 
 137     /**
 138      * Returns true if the specified object is equal to this
 139      * enum constant.
 140      *
 141      * @param other the object to be compared for equality with this object.
 142      * @return  true if the specified object is equal to this
 143      *          enum constant.
 144      */
 145     public final boolean equals(Object other) {
 146         return this==other;
 147     }
 148 
 149     /**
 150      * Returns a hash code for this enum constant.
 151      *
 152      * @return a hash code for this enum constant.
 153      */
 154     public final int hashCode() {
 155         return super.hashCode();
 156     }
 157 
 158     /**
 159      * Throws CloneNotSupportedException.  This guarantees that enums
 160      * are never cloned, which is necessary to preserve their "singleton"
 161      * status.
 162      *
 163      * @return (never returns)
 164      */
 165     protected final Object clone() throws CloneNotSupportedException {
 166         throw new CloneNotSupportedException();
 167     }
 168 
 169     /**
 170      * Compares this enum with the specified object for order.  Returns a
 171      * negative integer, zero, or a positive integer as this object is less
 172      * than, equal to, or greater than the specified object.
 173      *
 174      * Enum constants are only comparable to other enum constants of the
 175      * same enum type.  The natural order implemented by this
 176      * method is the order in which the constants are declared.
 177      */
 178     public final int compareTo(E o) {
 179         Enum<?> other = (Enum<?>)o;
 180         Enum<E> self = this;
 181         if (self.getClass() != other.getClass() && // optimization
 182             self.getDeclaringClass() != other.getDeclaringClass())
 183             throw new ClassCastException();
 184         return self.ordinal - other.ordinal;
 185     }
 186 
 187     /**
 188      * Returns the Class object corresponding to this enum constant's
 189      * enum type.  Two enum constants e1 and  e2 are of the
 190      * same enum type if and only if
 191      *   e1.getDeclaringClass() == e2.getDeclaringClass().
 192      * (The value returned by this method may differ from the one returned
 193      * by the {@link Object#getClass} method for enum constants with
 194      * constant-specific class bodies.)
 195      *
 196      * @return the Class object corresponding to this enum constant's
 197      *     enum type
 198      */
 199     @SuppressWarnings("unchecked")
 200     public final Class<E> getDeclaringClass() {
 201         Class<?> clazz = getClass();
 202         Class<?> zuper = clazz.getSuperclass();
 203         return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
 204     }
 205 
 206     /**
 207      * Returns the enum constant of the specified enum type with the
 208      * specified name.  The name must match exactly an identifier used
 209      * to declare an enum constant in this type.  (Extraneous whitespace
 210      * characters are not permitted.)
 211      *
 212      * <p>Note that for a particular enum type {@code T}, the
 213      * implicitly declared {@code public static T valueOf(String)}
 214      * method on that enum may be used instead of this method to map
 215      * from a name to the corresponding enum constant.  All the
 216      * constants of an enum type can be obtained by calling the
 217      * implicit {@code public static T[] values()} method of that
 218      * type.
 219      *
 220      * @param <T> The enum type whose constant is to be returned
 221      * @param enumType the {@code Class} object of the enum type from which
 222      *      to return a constant
 223      * @param name the name of the constant to return
 224      * @return the enum constant of the specified enum type with the
 225      *      specified name
 226      * @throws IllegalArgumentException if the specified enum type has
 227      *         no constant with the specified name, or the specified
 228      *         class object does not represent an enum type
 229      * @throws NullPointerException if {@code enumType} or {@code name}
 230      *         is null
 231      * @since 1.5
 232      */
 233     public static <T extends Enum<T>> T valueOf(Class<T> enumType,
 234                                                 String name) {
 235         T result = enumType.enumConstantDirectory().get(name);
 236         if (result != null)
 237             return result;
 238         if (name == null)
 239             throw new NullPointerException("Name is null");
 240         throw new IllegalArgumentException(
 241             "No enum constant " + enumType.getCanonicalName() + "." + name);
 242     }
 243 
 244     /**
 245      * enum classes cannot have finalize methods.
 246      */
 247     @SuppressWarnings("deprecation")
 248     protected final void finalize() { }
 249 
 250     /**
 251      * prevent default deserialization
 252      */
 253     private void readObject(ObjectInputStream in) throws IOException,
 254         ClassNotFoundException {
 255         throw new InvalidObjectException("can't deserialize enum");
 256     }
 257 
 258     private void readObjectNoData() throws ObjectStreamException {
 259         throw new InvalidObjectException("can't deserialize enum");
 260     }
 261 }