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 jdk.internal.lang.annotation.Foldable;
  29 
  30 import java.io.IOException;
  31 import java.io.InvalidObjectException;
  32 import java.io.ObjectInputStream;
  33 import java.io.ObjectStreamException;
  34 import java.io.Serializable;
  35 import java.lang.constant.ClassDesc;
  36 import java.lang.constant.Constable;
  37 import java.lang.constant.ConstantDesc;
  38 import java.lang.constant.ConstantDescs;
  39 import java.lang.constant.DynamicConstantDesc;
  40 import java.lang.invoke.MethodHandles;
  41 import java.util.Optional;
  42 
  43 import static java.util.Objects.requireNonNull;
  44 
  45 /**
  46  * This is the common base class of all Java language enumeration types.
  47  *
  48  * More information about enums, including descriptions of the
  49  * implicitly declared methods synthesized by the compiler, can be
  50  * found in section 8.9 of
  51  * <cite>The Java&trade; Language Specification</cite>.
  52  *
  53  * <p> Note that when using an enumeration type as the type of a set
  54  * or as the type of the keys in a map, specialized and efficient
  55  * {@linkplain java.util.EnumSet set} and {@linkplain
  56  * java.util.EnumMap map} implementations are available.
  57  *
  58  * @param <E> The enum type subclass
  59  * @serial exclude
  60  * @author  Josh Bloch
  61  * @author  Neal Gafter
  62  * @see     Class#getEnumConstants()
  63  * @see     java.util.EnumSet
  64  * @see     java.util.EnumMap
  65  * @since   1.5
  66  */
  67 @SuppressWarnings("serial") // No serialVersionUID needed due to
  68                             // special-casing of enum types.
  69 public abstract class Enum<E extends Enum<E>>
  70         implements Constable, Comparable<E>, Serializable {
  71     /**
  72      * The name of this enum constant, as declared in the enum declaration.
  73      * Most programmers should use the {@link #toString} method rather than
  74      * accessing this field.
  75      */
  76     private final String name;
  77 
  78     /**
  79      * Returns the name of this enum constant, exactly as declared in its
  80      * enum declaration.
  81      *
  82      * <b>Most programmers should use the {@link #toString} method in
  83      * preference to this one, as the toString method may return
  84      * a more user-friendly name.</b>  This method is designed primarily for
  85      * use in specialized situations where correctness depends on getting the
  86      * exact name, which will not vary from release to release.
  87      *
  88      * @return the name of this enum constant
  89      */
  90     public final String name() {
  91         return name;
  92     }
  93 
  94     /**
  95      * The ordinal of this enumeration constant (its position
  96      * in the enum declaration, where the initial constant is assigned
  97      * an ordinal of zero).
  98      *
  99      * Most programmers will have no use for this field.  It is designed
 100      * for use by sophisticated enum-based data structures, such as
 101      * {@link java.util.EnumSet} and {@link java.util.EnumMap}.
 102      */
 103     private final int ordinal;
 104 
 105     /**
 106      * Returns the ordinal of this enumeration constant (its position
 107      * in its enum declaration, where the initial constant is assigned
 108      * an ordinal of zero).
 109      *
 110      * Most programmers will have no use for this method.  It is
 111      * designed for use by sophisticated enum-based data structures, such
 112      * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
 113      *
 114      * @return the ordinal of this enumeration constant
 115      */
 116     public final int ordinal() {
 117         return ordinal;
 118     }
 119 
 120     /**
 121      * Sole constructor.  Programmers cannot invoke this constructor.
 122      * It is for use by code emitted by the compiler in response to
 123      * enum type declarations.
 124      *
 125      * @param name - The name of this enum constant, which is the identifier
 126      *               used to declare it.
 127      * @param ordinal - The ordinal of this enumeration constant (its position
 128      *         in the enum declaration, where the initial constant is assigned
 129      *         an ordinal of zero).
 130      */
 131     protected Enum(String name, int ordinal) {
 132         this.name = name;
 133         this.ordinal = ordinal;
 134     }
 135 
 136     /**
 137      * Returns the name of this enum constant, as contained in the
 138      * declaration.  This method may be overridden, though it typically
 139      * isn't necessary or desirable.  An enum type should override this
 140      * method when a more "programmer-friendly" string form exists.
 141      *
 142      * @return the name of this enum constant
 143      */
 144     public String toString() {
 145         return name;
 146     }
 147 
 148     /**
 149      * Returns true if the specified object is equal to this
 150      * enum constant.
 151      *
 152      * @param other the object to be compared for equality with this object.
 153      * @return  true if the specified object is equal to this
 154      *          enum constant.
 155      */
 156     public final boolean equals(Object other) {
 157         return this==other;
 158     }
 159 
 160     /**
 161      * Returns a hash code for this enum constant.
 162      *
 163      * @return a hash code for this enum constant.
 164      */
 165     public final int hashCode() {
 166         return super.hashCode();
 167     }
 168 
 169     /**
 170      * Throws CloneNotSupportedException.  This guarantees that enums
 171      * are never cloned, which is necessary to preserve their "singleton"
 172      * status.
 173      *
 174      * @return (never returns)
 175      */
 176     protected final Object clone() throws CloneNotSupportedException {
 177         throw new CloneNotSupportedException();
 178     }
 179 
 180     /**
 181      * Compares this enum with the specified object for order.  Returns a
 182      * negative integer, zero, or a positive integer as this object is less
 183      * than, equal to, or greater than the specified object.
 184      *
 185      * Enum constants are only comparable to other enum constants of the
 186      * same enum type.  The natural order implemented by this
 187      * method is the order in which the constants are declared.
 188      */
 189     public final int compareTo(E o) {
 190         Enum<?> other = (Enum<?>)o;
 191         Enum<E> self = this;
 192         if (self.getClass() != other.getClass() && // optimization
 193             self.getDeclaringClass() != other.getDeclaringClass())
 194             throw new ClassCastException();
 195         return self.ordinal - other.ordinal;
 196     }
 197 
 198     /**
 199      * Returns the Class object corresponding to this enum constant's
 200      * enum type.  Two enum constants e1 and  e2 are of the
 201      * same enum type if and only if
 202      *   e1.getDeclaringClass() == e2.getDeclaringClass().
 203      * (The value returned by this method may differ from the one returned
 204      * by the {@link Object#getClass} method for enum constants with
 205      * constant-specific class bodies.)
 206      *
 207      * @return the Class object corresponding to this enum constant's
 208      *     enum type
 209      */
 210     @SuppressWarnings("unchecked")
 211     public final Class<E> getDeclaringClass() {
 212         Class<?> clazz = getClass();
 213         Class<?> zuper = clazz.getSuperclass();
 214         return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
 215     }
 216 
 217     /**
 218      * Returns an enum descriptor {@code EnumDesc} for this instance, if one can be
 219      * constructed, or an empty {@link Optional} if one cannot be.
 220      *
 221      * @return An {@link Optional} containing the resulting nominal descriptor,
 222      * or an empty {@link Optional} if one cannot be constructed.
 223      * @since 12
 224      */
 225     @Override
 226     public final Optional<EnumDesc<E>> describeConstable() {
 227         return getDeclaringClass()
 228                 .describeConstable()
 229                 .map(c -> EnumDesc.of(c, name));
 230     }
 231 
 232     /**
 233      * Returns the enum constant of the specified enum type with the
 234      * specified name.  The name must match exactly an identifier used
 235      * to declare an enum constant in this type.  (Extraneous whitespace
 236      * characters are not permitted.)
 237      *
 238      * <p>Note that for a particular enum type {@code T}, the
 239      * implicitly declared {@code public static T valueOf(String)}
 240      * method on that enum may be used instead of this method to map
 241      * from a name to the corresponding enum constant.  All the
 242      * constants of an enum type can be obtained by calling the
 243      * implicit {@code public static T[] values()} method of that
 244      * type.
 245      *
 246      * @param <T> The enum type whose constant is to be returned
 247      * @param enumType the {@code Class} object of the enum type from which
 248      *      to return a constant
 249      * @param name the name of the constant to return
 250      * @return the enum constant of the specified enum type with the
 251      *      specified name
 252      * @throws IllegalArgumentException if the specified enum type has
 253      *         no constant with the specified name, or the specified
 254      *         class object does not represent an enum type
 255      * @throws NullPointerException if {@code enumType} or {@code name}
 256      *         is null
 257      * @since 1.5
 258      */
 259     public static <T extends Enum<T>> T valueOf(Class<T> enumType,
 260                                                 String name) {
 261         T result = enumType.enumConstantDirectory().get(name);
 262         if (result != null)
 263             return result;
 264         if (name == null)
 265             throw new NullPointerException("Name is null");
 266         throw new IllegalArgumentException(
 267             "No enum constant " + enumType.getCanonicalName() + "." + name);
 268     }
 269 
 270     /**
 271      * enum classes cannot have finalize methods.
 272      */
 273     @SuppressWarnings("deprecation")
 274     protected final void finalize() { }
 275 
 276     /**
 277      * prevent default deserialization
 278      */
 279     private void readObject(ObjectInputStream in) throws IOException,
 280         ClassNotFoundException {
 281         throw new InvalidObjectException("can't deserialize enum");
 282     }
 283 
 284     private void readObjectNoData() throws ObjectStreamException {
 285         throw new InvalidObjectException("can't deserialize enum");
 286     }
 287 
 288     /**
 289      * A <a href="package-summary.html#nominal">nominal descriptor</a> for an
 290      * {@code enum} constant.
 291      *
 292      * @param <E> the type of the enum constant
 293      *
 294      * @since 12
 295      */
 296     public static final class EnumDesc<E extends Enum<E>>
 297             extends DynamicConstantDesc<E> {
 298 
 299         /**
 300          * Constructs a nominal descriptor for the specified {@code enum} class and name.
 301          *
 302          * @param constantType a {@link ClassDesc} describing the {@code enum} class
 303          * @param constantName the unqualified name of the enum constant
 304          * @throws NullPointerException if any argument is null
 305          * @jvms 4.2.2 Unqualified Names
 306          */
 307         private EnumDesc(ClassDesc constantType, String constantName) {
 308             super(ConstantDescs.BSM_ENUM_CONSTANT, requireNonNull(constantName), requireNonNull(constantType));
 309         }
 310 
 311         /**
 312          * Returns a nominal descriptor for the specified {@code enum} class and name
 313          *
 314          * @param <E> the type of the enum constant
 315          * @param enumClass a {@link ClassDesc} describing the {@code enum} class
 316          * @param constantName the unqualified name of the enum constant
 317          * @return the nominal descriptor
 318          * @throws NullPointerException if any argument is null
 319          * @jvms 4.2.2 Unqualified Names
 320          * @since 12
 321          */
 322         @Foldable
 323         public static<E extends Enum<E>> EnumDesc<E> of(ClassDesc enumClass,
 324                                                         String constantName) {
 325             return new EnumDesc<>(enumClass, constantName);
 326         }
 327 
 328         @Override
 329         @SuppressWarnings("unchecked")
 330         public E resolveConstantDesc(MethodHandles.Lookup lookup)
 331                 throws ReflectiveOperationException {
 332             return Enum.valueOf((Class<E>) constantType().resolveConstantDesc(lookup), constantName());
 333         }
 334 
 335         @Override
 336         public String toString() {
 337             return String.format("EnumDesc[%s.%s]", constantType().displayName(), constantName());
 338         }
 339 
 340         @Override
 341         public Optional<? extends ConstantDesc> describeConstable() {
 342             return Optional.empty();
 343         }
 344     }
 345 }