关于java枚举使用和理解。

前言

在介绍枚举之前,先说说另外一个名词:[魔法数字]。魔法数字,是指在代码中直接出现的数值。
如:user.setStatus(1);
其中的数值1即为[魔法数字],你很难直观的理解1所代表的含义。至少第一眼,你会疑惑1代表的是什么。
为了避免这点,在开发时,我想你会添加注释。

虽然注释是一件好事情,但是如果代码本身就能很好的自说明,我想你一定非常乐意不写这个注释。因为它不会让你有任何心理负担。

另外有一个想法我觉得不错:
当你能把代码做到很好的抽象时 ——[这时代码已经简洁了不少]
当你在定义方法名/变量名时能做到很好的自说明 ——[这时大部分代码,你已经一看就能明白了]
最后,再加上适当的注释。我想这代码,肯定很有艺术感

PS:写代码时,对每一个变量的命名都请仔细思考,慎重。

而我的理解,枚举的诞生就是为了更好的解决上面的问题,提高代码的自说明。

另外枚举还有一个非常重要的好处:编译期间检查问题,数据的校验(方法参数定义的使用)等等。
这些在文章后面会一一提到。

言归正传

JAVA枚举(enum),JDK 1.5之后引入,存在于java.lang包内。它(enum)与class,interface的地位相同,用来定义枚举类。实际上枚举类是一个特殊的类,它也可以定义自己的方法,属性,构造器等,甚至可以实现接口。

api文档中,java.lang.Enum描述(大致):

//所有Java语言枚举类型的公共基本类。(注意Enum为抽象类)
public abstract class Enum<E extends Enum<E>>extends Object implements Comparable<E>, Serializable{
    ......
}

PS:文章最后附录了完整的java.lang.Enum,有兴趣的可以看一看

我们先来定义一个简单的enum(如下):

public enum Color{
    RED,BLUE,BLACK,YELLOW
}

ps:别去追究它为什么这么写,因为这是语法。
它也等价于:

public enum Color{
    RED(),BLUE(),BLACK(),YELLOW();
}

总结:
1.用enum关键字来定义枚举类。
2.显示的列出枚举值(请在第一行就这么做,并大写),用逗号隔开。

本质上:Color枚举类字节码代码(大致):

//注意几个地方:1.类的修饰为final;2.RED的类型,和修饰词;
public final class enums.Color extends java.lang.Enum<enums.Color> {
    public static final enums.Color RED;
    public static final enums.Color BLUE;
    public static final enums.Color BLACK;
    public static final enums.Color YELLOW;
    .........
}

由此可以得出枚举的一些本质:

(1)使用enum定义的枚举类,本质上是class类(我还是想用[有些特殊]来形容),只是它默认直接继承了java.lang.Enum类。[请把它当作class看待]

(2)枚举值(RED,BLUE…..)本质上是枚举Color对象,并且他们是final修饰的静态常量。这些值我们一般使用构造器的方式去初始化(后面会提到)。

(3)枚举类的构造器只能使用private访问控制符,哪怕是隐藏的构造器,它的访问控制符也是private。
PS:这点也很好理解,当需要我们使用构造器时。
无非是这么两种情况:
1.需要创建一个实例;然而枚举里面的枚举值是静态的,我们不需要通过创建实例来得到它。
2.需要初始化属性;我想如果你用枚举,就一定不会去这么做。因为那是常量并且是final。

(4)使用enum定义非抽象的枚举类默认会使用final修饰。但是(如):当枚举内有抽象方法时,该枚举类即为非抽象枚举类,不会被final修饰,这意味着可以被继承。(在后面还会提到,如果无法理解请先跳过)。

实际使用:

1.如果需要使用枚举类的某个实例,可以使用“枚举类.某个实例”的形式,例如Color.RED。注意,这里只是获取实例。实际使用中,获取实例只是第一步,后续还有一个取值的过程(后面给大家介绍)。

public class Test {
    public static void querColor(Color c) {
        switch (c) {
        case RED:
            System.out.println("我选了红色");
            break;
        case BLUE:
            System.out.println("我选了蓝色");
            break;
        case BLACK:
            System.out.println("我换了黑色");
            break;
        case YELLOW:
            System.out.println("我选了黄色");
            break;
        }
    }
    public static void main(String[] args) {
        queryColor(Color.RED); //枚举取实例
    }
}

JDK1.5增加枚举后对switch也进行了扩展,switch的条件表达式可以使用枚举类型。当switch条件表达式使用枚举类型时,case中的值可以直接使用枚举值名字。

2.我们往往在使用枚举时就希望枚举对象(枚举值)是不可变的。即枚举类的所有Field都应该用final修饰(它本身也是这么做的)。在这里我们一般使用构造器给这些属性初始化值。(或者在定义Field时指定默认值,或者在初始化块中指定初始值,但这两种情况不推荐)。
在实际开发过程中,我们根据业务需求,在定义枚举类时数据结构都会比Color复杂。如:UserTypeEnum

public enum UserTypeEnum {
    ADMINISTRATOR(0, "管理员"), SHOP(2, "门店"), WAITER(1, "小二"), SELLER(3, "销售");  

    private Integer code; 
    private String  desc;

    private UserTypeEnum(Integer code, String desc){
        this.setCode(code);
        this.setDesc(desc);
    }

    public String getDesc() {
        return desc;
    }
    public Integer getCode() {
        return code;
    }
    //**不应该存在set方法。**
}

上面程序中 ADMINISTRATOR(0, “管理员”), SHOP(2, “门店”), WAITER(1, “小二”), SELLER(3, “销售”),等同于如下代码:

//这点非常关键
private static final UserTypeEnum ADMINISTRATOR=new UserTypeEnum(0, "管理员");
private static final UserTypeEnum SHOP=new UserTypeEnum(2, "门店"),;
private static final UserTypeEnum WAITER=new UserTypeEnum(1, "小二");
private static final UserTypeEnum SELLER=new UserTypeEnum(3, "销售");

到了这里你需要好好理解一下,既然等价于new UserTypeEnum(2, "门店") ...我想你应该也能明白为什么需要写显示的带参构造器。

PS:如果枚举值括号内没有值(理解为调用无参构造),是可以省略的。这也很好的解释了文章开头:

ADMINISTRATOR  等价于  ADMINISTRATOR()

取值的过程:

UserTypeEnum.SHOP.getDesc()  //即能得到"门店"
UserTypeEnum.SHOP.getCode()  //即能得到2

这个时候你就会发现,他真的就是一个[普通]的class。是不是很简单!

3.枚举类也可以实现一个或多个接口。与普通类实现一个或多个接口完全一样,枚举类实现一个或多个接口时,也需要实现该接口所包含的方法。

public interface PrintColor {
    void print();
}

public enum Color implements PrintColor{
    RED, BLUE, BLACK, YELLOW;
    @Override
    public void print() {
        System.out.println("print......");
    }

}

如果由枚举类来实现接口里的方法,则每个枚举类(枚举值)对象在调用该方法时,都有相同的行为方式(因为方法体完全一样)。如果需要每个枚举对象在调用该方法时,呈现出不同的行为方式,则可以让每个枚举对象分别来实现该方法。

public interface PrintColor {
    void print();
}

public enum Color implements PrintColor {
    RED {
        @Override
        public void print() {
            System.out.println("画红色!");
        }
    },
    BLUE {
        @Override
        public void print() {
            System.out.println("画蓝色!");
        }
    },
    BLACK {
        @Override
        public void print() {
            System.out.println("画黑色!");
        }
    },
    YELLOW {
        @Override
        public void print() {
            System.out.println("画黄色!");
        }
    };
}

RED、BLUE、BLACK和YELLOW实际上是Color匿名子类的实例,而不是Color类的实例。我的理解是这个时候Color变成了抽象类。

注意:并不是所有的枚举类都使用了final修饰。非抽象的枚举类才默认使用final修饰。对于一个抽象的枚举类而言(只要它包含了抽象方法,它就是抽象枚举类),系统会默认使用abstract修饰,而不是使用final修饰。

每个枚举对象提供不同的实现方式,从而让不同的枚举对象调用该方法时,具有不同的行为方式。

4.如果不使用接口,而是直接在枚举类中定义一个抽象方法,然后再让每个枚举对象提供不同的实现方式。

public enum Color {
    RED {
        @Override
        public void print() {
            System.out.println("画红色!");
        }
    },
    BLUE {
        @Override
        public void print() {
            System.out.println("画蓝色!");
        }
    },
    BLACK {
        @Override
        public void print() {
            System.out.println("画黑色!");
        }
    },
    YELLOW {
        @Override
        public void print() {
            System.out.println("画黄色!");
        }
    };
    abstract void print();
}

Color是一个包含抽象方法的枚举类,但是“public enum Color”没有使用abstract修饰,这是因为编译器(javac)会在编译生成.class时,自动添加abstract。同时,因为Color包含一个抽象方法,所以它的所有枚举对象都必须实现抽象方法,否则编译器会报错。

另外在实际使用中,我们也会用枚举来做其他事情:
比如说,
public void modifyListing(List<Long> itemIds, Long status)
public void modifyListing(List<Long> itemIds, MallItemStatusEnum status)
这两个方法是同一个方法,只是参数一个用了Long类型的,另一个用了MallItemStatusEnum枚举类型的。
而区别好处:
前者,只要随便传一个值都行。事实上如果这么做,你肯定会在方法里面做一个校验,确保这个值不会出现问题。
而后者不需要,最多进行一个判断status是否为空操作。

附录:java.lang.Enum

/*
 * %W% %E%
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;

import java.io.Serializable;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;

/**
 * This is the common base class of all Java language enumeration types.
 *
 * @author  Josh Bloch
 * @author  Neal Gafter
 * @version %I%, %G%
 * @since   1.5
 */
public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {
    /**
     * The name of this enum constant, as declared in the enum declaration.
     * Most programmers should use the {@link #toString} method rather than
     * accessing this field.
     */
    private final String name;

    /**
     * Returns the name of this enum constant, exactly as declared in its
     * enum declaration.
     * 
     * <b>Most programmers should use the {@link #toString} method in
     * preference to this one, as the toString method may return
     * a more user-friendly name.</b>  This method is designed primarily for
     * use in specialized situations where correctness depends on getting the
     * exact name, which will not vary from release to release.
     *
     * @return the name of this enum constant
     */
    public final String name() {
    return name;
    }

    /**
     * The ordinal of this enumeration constant (its position
     * in the enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     * 
     * Most programmers will have no use for this field.  It is designed
     * for use by sophisticated enum-based data structures, such as
     * {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     */
    private final int ordinal;

    /**
     * Returns the ordinal of this enumeration constant (its position
     * in its enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     * 
     * Most programmers will have no use for this method.  It is
     * designed for use by sophisticated enum-based data structures, such
     * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     *
     * @return the ordinal of this enumeration constant
     */
    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;
    }

    /**
     * Returns the name of this enum constant, as contained in the
     * declaration.  This method may be overridden, though it typically
     * isn't necessary or desirable.  An enum type should override this
     * method when a more "programmer-friendly" string form exists.
     *
     * @return the name of this enum constant
     */
    public String toString() {
    return name;
    }

    /**
     * Returns true if the specified object is equal to this
     * enum constant.
     *
     * @param other the object to be compared for equality with this object.
     * @return  true if the specified object is equal to this
     *          enum constant.
     */
    public final boolean equals(Object other) { 
        return this==other;
    }

    /**
     * Returns a hash code for this enum constant.
     *
     * @return a hash code for this enum constant.
     */
    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();
    }

    /**
     * Compares this enum with the specified object for order.  Returns a
     * negative integer, zero, or a positive integer as this object is less
     * than, equal to, or greater than the specified object.
     * 
     * Enum constants are only comparable to other enum constants of the
     * same enum type.  The natural order implemented by this
     * method is the order in which the constants are declared.
     */
    public final int compareTo(E o) {
    Enum other = (Enum)o;
    Enum 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
     */
    public final Class<E> getDeclaringClass() {
    Class clazz = getClass();
    Class zuper = clazz.getSuperclass();
    return (zuper == Enum.class) ? clazz : zuper;
    }

    /**
     * Returns the enum constant of the specified enum type with the
     * specified name.  The name must match exactly an identifier used
     * to declare an enum constant in this type.  (Extraneous whitespace
     * characters are not permitted.) 
     *
     * @param enumType the <tt>Class</tt> object of the enum type from which
     *      to return a constant
     * @param name the name of the constant to return
     * @return the enum constant of the specified enum type with the
     *      specified name
     * @throws IllegalArgumentException if the specified enum type has
     *         no constant with the specified name, or the specified
     *         class object does not represent an enum type
     * @throws NullPointerException if <tt>enumType</tt> or <tt>name</tt>
     *         is null
     * @since 1.5
     */
    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 const " + enumType +"." + name);
    }

    /**
      * 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 classes cannot have finalize methods.
     */
    protected final void finalize() { }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值