EnumUtils

org.apache.commons.lang3.EnumUtils

getEnum() 根据枚举name获取枚举实例

public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName) {
    return getEnum(enumClass, enumName, null);

Enum枚举

每个枚举都是抽象类 java.lang.Enum 的子类,都可以访问Enum类提供的方法,比如hashCode、name、valueOf等,其中valueOf方法会把一个String类型的名称转变成枚举项,也就是在枚举项中查找字面值和该参数相等的枚举项。

实际上在使用关键字enum创建枚举类型并编译后,编译器会为我们生成一个相关的类,这个类继承了Java API中的java.lang.Enum类,也就是说通过关键字enum创建枚举类型在编译后事实上也是一个类类型而且该类继承自java.lang.Enum类。

枚举的构造方法都是private的

枚举的构造方法都是默认 private 的,如果改为 public 会报错,如果显式写出 private IDE 会提示 Modifier ‘private’ is redundant for enum constructors

Enum.valueOf(Class, String)

valueOf 静态方法会把一个 String 类型的名称转变成枚举项,也就是在枚举项中查找字面值和该参数相等的枚举项。

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

参数
enumType – 这是枚举类型,返回一个常量的类的对象。
name – 这是常量,要返回的名称。
返回值
此方法返回具有指定名称的枚举类型的枚举常量。
异常
IllegalArgumentException – 如果指定的枚举类型没有常量指定名称,或指定的类对象不表示枚举类型。
NullPointerException – 如果 enumType 或 name 为 null.

valudOf方法通过反射从枚举类的常量声明中查找,若找到就直接返回,若找不到则抛出无效参数异常。valueOf的本意是保护编码的枚举安全性,使其不产生空枚举对象,简化枚举操作,但是却又引入了一个我们无法避免的IllegalArgumentException异常。

the name must match exactly an identifier used to declare an enum constant in this type
name 参数必须和枚举name完全匹配,大小写都不能错
例如:
Color myColor = Enum.valueOf(Color.class, "RED");

Color.valueOf(String)

其实每个具体的枚举类都有一个 valueOf(String) 方法,直接用这个方法就行,没必要使用 Enum 类的静态方法:
Color color = Color.valueOf("RED");

public enum Color {
    RED("红色"),
    BLUE("蓝色");
    private String desc;
    Color(String desc) {
        this.desc = desc;
    public String getDesc() {
        return desc;
    public static void main(String[] args) {
        // 大小写不匹配,错误
        try {
            Color.valueOf("red");
        } catch (IllegalArgumentException e) {
            System.out.println(e.toString());
        // Enum 类的静态方法
        Color myColor = Enum.valueOf(Color.class, "RED");
        System.out.println("myColor: " + myColor);
        // 枚举类自己的静态方法
        Color myColor2 = Color.valueOf("BLUE");
        System.out.println("myColor2: " + myColor2);
java.lang.IllegalArgumentException: No enum constant com.nio.uds.user.service.Color.red
myColor: RED
myColor2: BLUE

深入理解Java枚举类型(enum)
https://blog.csdn.net/javazejian/article/details/71333103

Java 枚举(enum) 详解7种常见的用法
https://blog.csdn.net/qq_27093465/article/details/52180865

Java 中的枚举 (enum)
https://www.jianshu.com/p/46dbd930f6a2

深度分析Java的枚举类型—-枚举的线程安全性及序列化问题
https://www.hollischuang.com/archives/197

name()toString()

name()toString() 之间的主要区别是
name() 是一个 final 方法,因此它不能被覆盖。
toString() 方法返回的值与 name() 默认值相同,但 toString() 可以被 Enum 的子类覆盖。
因此,如果需要字段本身的名称,请使用 name()。如果需要字段值的字符串表示,请使用 toString()。

public enum WeekDay {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase();

在这个例子中,
WeekDay.MONDAY.name() 返回 MONDAY
WeekDay.MONDAY.toString() 返回 Monday

WeekDay.valueOf(WeekDay.MONDAY.name()) 返回WeekDay.MONDAY
WeekDay.valueOf(WeekDay.MONDAY.toString())会抛出IllegalArgumentException。

What is the difference between Enum.name() and Enum.toString()? [duplicate]
https://stackoverflow.com/questions/18031125/what-is-the-difference-between-enum-name-and-enum-tostring/18031576

枚举比较

使用 == 和使用equals方法的执行结果是一样的。

因为在Enum类里面,已经重写了equals方法,而方法里面比较就是直接使用==,来比较2个对象的。所以,你在外边直接使用==也是可以的。

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

为什么枚举可以用==比较?

JLS 8.9 Enums 一个枚举类型除了定义的那些枚举常量外没有其他实例了。 试图明确地说明一种枚举类型是会导致编译期异常。在枚举中final clone方法确保枚举常量从不会被克隆,而且序列化机制会确保从不会因为反序列化而创造复制的实例。枚举类型的反射实例化也是被禁止的。总之,以上内容确保了除了定义的枚举常量之外,没有枚举类型实例。

因为每个枚举常量只有一个实例,所以如果在比较两个参考值,至少有一个涉及到枚举常量时,允许使用“==”代替equals()。

什么时候 == 和 equals 不一样?

== 不会抛出 NullPointerException

enum Color { BLACK, WHITE };
Color nothing = null;
if (nothing == Color.BLACK);      // runs fine
if (nothing.equals(Color.BLACK)); // throws NullPointerException

== 在编译期检测类型兼容性

enum Color { BLACK, WHITE };
enum Chiral { LEFT, RIGHT };
if (Color.BLACK.equals(Chiral.LEFT)); // compiles fine
if (Color.BLACK == Chiral.LEFT);      // DOESN'T COMPILE!!! Incompatible types!

比较java枚举成员使用equal还是==
https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/comparing-java-enum-members-or-equals.md

枚举使用举例

兼容Jackson序列化的枚举类

package com.madaimeng;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public enum AuthorizationType {
    UNKNOWN((byte) 0, "", "未知"),
    AUTHORIZED((byte) 1, "granted", "授权"),
    REVOKE((byte) 2, "revoked", "取消授权");
    private byte code; // 枚举的code,可用于和数据库字段映射
    private String mappingCode; // 对应的外系统code,用于接收外系统json数据时映射
    private String description; // 描述
    // 枚举的构造方法
    VehicleAuthorizationType(byte code, String mappingCode, String description) {
        this.code = code;
        this.mappingCode = mappingCode;
        this.description = description;
    public byte getCode() {
        return code;
    public String getMappingCode() {
        return mappingCode;
    public String getDescription() {
        return description;
    // 枚举内定义了两个map,分别用于根据外系统code查找对应的枚举值,和根据code查找对应的枚举值
    private static Map<Byte, VehicleAuthorizationType> codeMap = Maps.newHashMap();
    private static Map<String, VehicleAuthorizationType> mappingCodeMap = Maps.newHashMap();
    // 初始化两个map
    static {
        for (VehicleAuthorizationType value : VehicleAuthorizationType.values()) {
            codeMap.put(value.getCode(), value);
            mappingCodeMap.put(value.mappingCode, value);
        codeMap = Collections.unmodifiableMap(codeMap);
        mappingCodeMap = Collections.unmodifiableMap(mappingCodeMap);
    // 通过 @JsonCreator 标记为 jackson 反序列化构造方法,入参str是外系统code,即mappingCode
    @JsonCreator
    public static VehicleAuthorizationType getVehicleAuthorizationType(String str) {
        if (StringUtils.isBlank(str)) {
            return UNKNOWN;
        return mappingCodeMap.get(str);
    // 根据code查找对应的枚举类型
    public static VehicleAuthorizationType getByCode(byte code) {
        return codeMap.get(code);
    // 根据外系统code查找对应的枚举类型
    public static VehicleAuthorizationType getByMappingCode(String mappingCode) {
        return mappingCodeMap.get(mappingCode);

通过一个接口IEnum规范枚举类行为

通过一个接口 IEnum 规范枚举类行为

package com.masikkk.enums;
public interface IEnum<T> {
    public T getValue();
    public String getDesc();

所以定义的枚举类都实现这个接口

package com.masikkk.enums;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.masikkk.enums.IEnum;
import org.apache.commons.lang3.StringUtils;
public enum MobileType implements IEnum<String> {
    PERSONAL("私人手机"),
    WORK("工作手机");
    private String description;
    MobileType(String description) {
        this.description = description;
    @Override
    public String getValue() {
        return name();
    @Override
    public String getDesc() {
        return description;
    @JsonCreator
    public static MobileType getByName(String str) {
        return StringUtils.isBlank(str) ? null : MobileType.valueOf(str.trim().toUpperCase());

java.lang.Enum抽象类源码

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.
 * More information about enums, including descriptions of the
 * implicitly declared methods synthesized by the compiler, can be
 * found in section 8.9 of
 * <cite>The Java&trade; Language Specification</cite>.
 * <p> Note that when using an enumeration type as the type of a set
 * or as the type of the keys in a map, specialized and efficient
 * {@linkplain java.util.EnumSet set} and {@linkplain
 * java.util.EnumMap map} implementations are available.
 * @param <E> The enum type subclass
 * @author  Josh Bloch
 * @author  Neal Gafter
 * @see     Class#getEnumConstants()
 * @see     java.util.EnumSet
 * @see     java.util.EnumMap
 * @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; //枚举顺序值,从0开始
     * 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<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;
     * 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.)
     * <p>Note that for a particular enum type {@code T}, the
     * implicitly declared {@code public static T valueOf(String)}
     * method on that enum may be used instead of this method to map
     * from a name to the corresponding enum constant.  All the
     * constants of an enum type can be obtained by calling the
     * implicit {@code public static T[] values()} method of that
     * type.
     * @param <T> The enum type whose constant is to be returned
     * @param enumType the {@code Class} 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 {@code enumType} or {@code name}
     *         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 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");