zoukankan      html  css  js  c++  java
  • JVM中的枚举

    【问题】

      写代码过程中,定义了一组枚举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的,只有一份且值也无法被修改。

    【参考】

    https://www.cnblogs.com/alter888/p/9163612.html

  • 相关阅读:
    Windows2012中安装PHP-5.6.20+Apache httpd2.4.18+Composer+Laravel+MySQL5.7
    CentOS7安装使用MySQL
    使用passenger在Centos7部署Puma+Nginx+Ruby on Rails
    DOS和UNIX文本文件之间相互转换的方法
    CentOS7安装vim7.4
    Python多版本共存之pyenv
    我的Shell + VIM配置
    CentOS7安装Python3.5
    CentOS7系统下搭建Jenkins环境
    Windows系统下搭建Jenkins环境
  • 原文地址:https://www.cnblogs.com/bruceChan0018/p/15086311.html
Copyright © 2011-2022 走看看