ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

JVM中的枚举

2021-08-01 13:00:31  阅读:229  来源: 互联网

标签:ordinal return name enum 枚举 JVM final


【问题】

  写代码过程中,定义了一组枚举WEEKDAYS[MONDAY,TUESDAY,......]。此时,如果输入参数为一个WEEKDAYS的参数,我们对这个参数进行值判定的时候,到底用eaquals还是==去判断呢?在JVM中,枚举到底是如何存放的?<Effective Java>中说枚举是单例模式的最佳实现方式,为什么?

【查阅资料】

  使用javac将代码进行编译,并用javap命令查看编译之后的字节码文件:

  可以看到,枚举类经过编译器的处理,拥有以下特点:

  1. 构造函数私有;
  2. 类为final类,继承了java.lang.Enum<E>
  3. 定义了values()方法返回所有的枚举实例;
  4. valueOf可以根据枚举的字符串形式转为枚举类实例;

  这里,我们可以再看看java.lang.Enum<E>的实现:

public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {

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

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

    /**
     * Sole constructor.  Programmers cannot invoke this constructor.
     * It is for use by code emitted by the compiler in response to
     * enum type declarations.
     *
     * @param name - The name of this enum constant, which is the identifier
     *               used to declare it.
     * @param ordinal - The ordinal of this enumeration constant (its position
     *         in the enum declaration, where the initial constant is assigned
     *         an ordinal of zero).
     */
    protected Enum(String name, int ordinal) {
        this.name = name;
        this.ordinal = ordinal;
    }

    public String toString() {
        return name;
    }
    public final boolean equals(Object other) {
        return this==other;
    }

    public final int hashCode() {
        return super.hashCode();
    }

    /**
     * Throws CloneNotSupportedException.  This guarantees that enums
     * are never cloned, which is necessary to preserve their "singleton"
     * status.
     *
     * @return (never returns)
     */
    protected final Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

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

    /**
     * Returns the Class object corresponding to this enum constant's
     * enum type.  Two enum constants e1 and  e2 are of the
     * same enum type if and only if
     *   e1.getDeclaringClass() == e2.getDeclaringClass().
     * (The value returned by this method may differ from the one returned
     * by the {@link Object#getClass} method for enum constants with
     * constant-specific class bodies.)
     *
     * @return the Class object corresponding to this enum constant's
     *     enum type
     */
    @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 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);
    }

    /**
     * enum classes cannot have finalize methods.
     */
    protected final void finalize() { }

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

  对于枚举类型来说,equals与==是一样的。而name()和toString()也是一样的,都是返回枚举内部的name字段。为了保护这种单例形态,枚举不能进行clone()。所以,在使用枚举时,拿到枚举实例再进行A.toString().equals(B.toString())的比较是完全没有必要的,直接A==B来判断就好,因为枚举的定义就是static final的,只有一份且值也无法被修改。

 

 

 

标签:ordinal,return,name,enum,枚举,JVM,final
来源: https://www.cnblogs.com/bruceChan0018/p/15086311.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有