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