package java.lang;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
/*
* 可以看作是所有enum的包装类,不过Enum类是禁止直接继承的
*
* 示例:
* public enum Color {
* WHITE, BLACK
* }
*
* 等价于:
* public final class Color extends Enum<Color> {
* public static final Color WHITE = new Color("WHITE", 0);
* public static final Color BLACK = new Color("BLACK", 1);
*
* public Color(String name, int ordinal) {
* super(name, ordinal);
* }
*
* // ......
* }
*/
@SuppressWarnings("serial")
public abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable {
private final String name; // 枚举实例名称
private final int ordinal; // 枚举实例的值
protected Enum(String name, int ordinal) {
this.name = name;
this.ordinal = ordinal;
}
// 返回枚举实例名称
public final String name() {
return name;
}
// 返回枚举实例的值
public final int ordinal() {
return ordinal;
}
// 返回枚举类类对象
@SuppressWarnings("unchecked")
public final Class<E> getDeclaringClass() {
Class<?> clazz = getClass();
Class<?> zuper = clazz.getSuperclass();
return (zuper == Enum.class) ? (Class<E>) clazz : (Class<E>) zuper;
}
// 比较枚举实例的值;声明靠前的枚举,其"值"较小
public final int compareTo(E o) {
Enum<?> other = (Enum<?>) o;
Enum<E> self = this;
if(self.getClass() != other.getClass() && // optimization
self.getDeclaringClass() != other.getDeclaringClass()) {
throw new ClassCastException();
}
return self.ordinal - other.ordinal;
}
/*
* 获取枚举类enumType中名称为name的枚举实例,其他实例不受影响
* Color c = Enum.valueOf(Color.class, "WHITE");
*/
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) {
T result = enumType.enumConstantDirectory().get(name);
if(result != null) {
return result;
}
if(name == null) {
throw new NullPointerException("Name is null");
}
throw new IllegalArgumentException("No enum constant " + enumType.getCanonicalName() + "." + name);
}
/*▼ 继承自Object ████████████████████████████████████████████████████████████████████████████████┓ */
public final int hashCode() {
return super.hashCode();
}
public final boolean equals(Object other) {
return this == other;
}
public String toString() {
return name;
}
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
@SuppressWarnings("deprecation")
protected final void finalize() {
}
/*▲ 继承自Object ████████████████████████████████████████████████████████████████████████████████┛ */
/**
* prevent default deserialization
*/
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
throw new InvalidObjectException("can't deserialize enum");
}
private void readObjectNoData() throws ObjectStreamException {
throw new InvalidObjectException("can't deserialize enum");
}
}
包装类-Enum源码分析
最新推荐文章于 2022-12-30 15:50:39 发布