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