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