1 /*
2  * Copyright (c) 2003, 2017, 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  * @author  Josh Bloch
49  * @author  Neal Gafter
50  * @see     Class#getEnumConstants()
51  * @see     java.util.EnumSet
52  * @see     java.util.EnumMap
53  * @since   1.5
54  */

55 @SuppressWarnings("serial"// No serialVersionUID needed due to
56                             // special-casing of enum types.
57 public abstract class Enum<E extends Enum<E>>
58         implements Comparable<E>, Serializable {
59     /**
60      * The name of this enum constant, as declared in the enum declaration.
61      * Most programmers should use the {@link #toString} method rather than
62      * accessing this field.
63      */

64     private final String name;
65
66     /**
67      * Returns the name of this enum constant, exactly as declared in its
68      * enum declaration.
69      *
70      * <b>Most programmers should use the {@link #toString} method in
71      * preference to this one, as the toString method may return
72      * a more user-friendly name.</b>  This method is designed primarily for
73      * use in specialized situations where correctness depends on getting the
74      * exact name, which will not vary from release to release.
75      *
76      * @return the name of this enum constant
77      */

78     public final String name() {
79         return name;
80     }
81
82     /**
83      * The ordinal of this enumeration constant (its position
84      * in the enum declaration, where the initial constant is assigned
85      * an ordinal of zero).
86      *
87      * Most programmers will have no use for this field.  It is designed
88      * for use by sophisticated enum-based data structures, such as
89      * {@link java.util.EnumSet} and {@link java.util.EnumMap}.
90      */

91     private final int ordinal;
92
93     /**
94      * Returns the ordinal of this enumeration constant (its position
95      * in its enum declaration, where the initial constant is assigned
96      * an ordinal of zero).
97      *
98      * Most programmers will have no use for this method.  It is
99      * designed for use by sophisticated enum-based data structures, such
100      * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
101      *
102      * @return the ordinal of this enumeration constant
103      */

104     public final int ordinal() {
105         return ordinal;
106     }
107
108     /**
109      * Sole constructor.  Programmers cannot invoke this constructor.
110      * It is for use by code emitted by the compiler in response to
111      * enum type declarations.
112      *
113      * @param name - The name of this enum constant, which is the identifier
114      *               used to declare it.
115      * @param ordinal - The ordinal of this enumeration constant (its position
116      *         in the enum declaration, where the initial constant is assigned
117      *         an ordinal of zero).
118      */

119     protected Enum(String name, int ordinal) {
120         this.name = name;
121         this.ordinal = ordinal;
122     }
123
124     /**
125      * Returns the name of this enum constant, as contained in the
126      * declaration.  This method may be overridden, though it typically
127      * isn't necessary or desirable.  An enum type should override this
128      * method when a more "programmer-friendly" string form exists.
129      *
130      * @return the name of this enum constant
131      */

132     public String toString() {
133         return name;
134     }
135
136     /**
137      * Returns true if the specified object is equal to this
138      * enum constant.
139      *
140      * @param other the object to be compared for equality with this object.
141      * @return  true if the specified object is equal to this
142      *          enum constant.
143      */

144     public final boolean equals(Object other) {
145         return this==other;
146     }
147
148     /**
149      * Returns a hash code for this enum constant.
150      *
151      * @return a hash code for this enum constant.
152      */

153     public final int hashCode() {
154         return super.hashCode();
155     }
156
157     /**
158      * Throws CloneNotSupportedException.  This guarantees that enums
159      * are never cloned, which is necessary to preserve their "singleton"
160      * status.
161      *
162      * @return (never returns)
163      */

164     protected final Object clone() throws CloneNotSupportedException {
165         throw new CloneNotSupportedException();
166     }
167
168     /**
169      * Compares this enum with the specified object for order.  Returns a
170      * negative integer, zero, or a positive integer as this object is less
171      * than, equal to, or greater than the specified object.
172      *
173      * Enum constants are only comparable to other enum constants of the
174      * same enum type.  The natural order implemented by this
175      * method is the order in which the constants are declared.
176      */

177     public final int compareTo(E o) {
178         Enum<?> other = (Enum<?>)o;
179         Enum<E> self = this;
180         if (self.getClass() != other.getClass() && // optimization
181             self.getDeclaringClass() != other.getDeclaringClass())
182             throw new ClassCastException();
183         return self.ordinal - other.ordinal;
184     }
185
186     /**
187      * Returns the Class object corresponding to this enum constant's
188      * enum type.  Two enum constants e1 and  e2 are of the
189      * same enum type if and only if
190      *   e1.getDeclaringClass() == e2.getDeclaringClass().
191      * (The value returned by this method may differ from the one returned
192      * by the {@link Object#getClass} method for enum constants with
193      * constant-specific class bodies.)
194      *
195      * @return the Class object corresponding to this enum constant's
196      *     enum type
197      */

198     @SuppressWarnings("unchecked")
199     public final Class<E> getDeclaringClass() {
200         Class<?> clazz = getClass();
201         Class<?> zuper = clazz.getSuperclass();
202         return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
203     }
204
205     /**
206      * Returns the enum constant of the specified enum type with the
207      * specified name.  The name must match exactly an identifier used
208      * to declare an enum constant in this type.  (Extraneous whitespace
209      * characters are not permitted.)
210      *
211      * <p>Note that for a particular enum type {@code T}, the
212      * implicitly declared {@code public static T valueOf(String)}
213      * method on that enum may be used instead of this method to map
214      * from a name to the corresponding enum constant.  All the
215      * constants of an enum type can be obtained by calling the
216      * implicit {@code public static T[] values()} method of that
217      * type.
218      *
219      * @param <T> The enum type whose constant is to be returned
220      * @param enumType the {@code Class} object of the enum type from which
221      *      to return a constant
222      * @param name the name of the constant to return
223      * @return the enum constant of the specified enum type with the
224      *      specified name
225      * @throws IllegalArgumentException if the specified enum type has
226      *         no constant with the specified name, or the specified
227      *         class object does not represent an enum type
228      * @throws NullPointerException if {@code enumType} or {@code name}
229      *         is null
230      * @since 1.5
231      */

232     public static <T extends Enum<T>> T valueOf(Class<T> enumType,
233                                                 String name) {
234         T result = enumType.enumConstantDirectory().get(name);
235         if (result != null)
236             return result;
237         if (name == null)
238             throw new NullPointerException("Name is null");
239         throw new IllegalArgumentException(
240             "No enum constant " + enumType.getCanonicalName() + "." + name);
241     }
242
243     /**
244      * enum classes cannot have finalize methods.
245      */

246     @SuppressWarnings("deprecation")
247     protected final void finalize() { }
248
249     /**
250      * prevent default deserialization
251      */

252     private void readObject(ObjectInputStream in) throws IOException,
253         ClassNotFoundException {
254         throw new InvalidObjectException("can't deserialize enum");
255     }
256
257     private void readObjectNoData() throws ObjectStreamException {
258         throw new InvalidObjectException("can't deserialize enum");
259     }
260 }
261