JDK1.8源码解读之 Enum

470 阅读2分钟

概述

所有java语言枚举类的公共基础类。 使用枚举类作为一个set或者map中key的类型的时候,可以使用专门且有效的EnumSet或者EnumMap实现。

继承关系

public abstract class Enum<E extends Enum> implements Comparable, Serializable 实现了Comparable 和 Serializable接口,

成员属性

  • private final String name; 枚举声明中声明的该枚举常量的名称。大多数程序员应使用toString方法,而不是访问此字段。
  • private final int ordinal; 中文翻译是“序数”

构造器

构造函数里需要传递两个参数,一个是name,一个是ordinal。 也就是名称和序数。

protected Enum(String name, int ordinal) {
    this.name = name;
    this.ordinal = ordinal;
}

关键方法

name()

返回name

public final String name() {
    return name;
}
ordinal()

返回rodinal

public final int ordinal() {
    return ordinal;
}
equals()

判断相等,如果指定的Object和当前enum相等。则返回true。

public final boolean equals(Object other) {
    return this==other;
}
clone()

Enum是单例模式,不允许被clone

protected final Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
}
compareTo()

两个Enum比较,如果类型不一致,抛出异常。 类型一致,返回序号的差。

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;
}
getDeclaringClass()

返回与此枚举常量的枚举类型相对应的Class对象。

@SuppressWarnings("unchecked")
public final Class<E> getDeclaringClass() {
    Class<?> clazz = getClass();
    Class<?> zuper = clazz.getSuperclass();
    return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
}
valueOf()

返回具有指定名称的指定枚举类型的枚举常量。 名称必须与用于声明此类型的枚举常量的标识符完全匹配。 (不允许使用多余的空格字符。) 请注意,对于特定的枚举类型{@code T}, 可以使用对该枚举隐式声明的{@code public static T valueOf(String)}方法, 而不是使用此方法来映射对应的枚举常量的名称。 可以通过调用该类型的隐式{@code public static T [] values()}方法来获取枚举类型的所有常量。

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);
}
finalize()

阻止了finalize方法。final修饰符,表示不允许Enum的子类有自己的finalize方法。

protected final void finalize() { }
readObject()

阻止默认的反序列化,直接抛出异常。

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");
}

希望和大家多多交流


我16年毕业以后,做的是前端,目前打算深入学习java开发。内容有任何问题,欢迎各位小伙伴们指正,也希望小伙伴们给我点赞和关注,给我留言,一起交流讨论,共同进步。