1 7 8 package java.lang; 9 10 import java.io.Serializable ; 11 import java.io.IOException ; 12 import java.io.InvalidObjectException ; 13 import java.io.ObjectInputStream ; 14 import java.io.ObjectStreamException ; 15 16 24 public abstract class Enum<E extends Enum <E>> 25 implements Comparable <E>, Serializable { 26 31 private final String name; 32 33 45 public final String name() { 46 return name; 47 } 48 49 58 private final int ordinal; 59 60 71 public final int ordinal() { 72 return ordinal; 73 } 74 75 86 protected Enum(String name, int ordinal) { 87 this.name = name; 88 this.ordinal = ordinal; 89 } 90 91 99 public String toString() { 100 return name; 101 } 102 103 111 public final boolean equals(Object other) { 112 return this==other; 113 } 114 115 120 public final int hashCode() { 121 return System.identityHashCode(this); 122 } 123 124 131 protected final Object clone() throws CloneNotSupportedException { 132 throw new CloneNotSupportedException (); 133 } 134 135 144 public final int compareTo(E o) { 145 Enum other = (Enum )o; 146 Enum self = this; 147 if (self.getClass() != other.getClass() && self.getDeclaringClass() != other.getDeclaringClass()) 149 throw new ClassCastException (); 150 return self.ordinal - other.ordinal; 151 } 152 153 165 public final Class <E> getDeclaringClass() { 166 Class clazz = getClass(); 167 Class zuper = clazz.getSuperclass(); 168 return (zuper == Enum .class) ? clazz : zuper; 169 } 170 171 189 public static <T extends Enum <T>> T valueOf(Class <T> enumType, 190 String name) { 191 T result = enumType.enumConstantDirectory().get(name); 192 if (result != null) 193 return result; 194 if (name == null) 195 throw new NullPointerException ("Name is null"); 196 throw new IllegalArgumentException ( 197 "No enum const " + enumType +"." + name); 198 } 199 200 203 private void readObject(ObjectInputStream in) throws IOException , 204 ClassNotFoundException { 205 throw new InvalidObjectException ("can't deserialize enum"); 206 } 207 208 private void readObjectNoData() throws ObjectStreamException { 209 throw new InvalidObjectException ("can't deserialize enum"); 210 } 211 } 212 | Popular Tags |