16 min to read
Java
学习Java枚举(Enum)
Java枚举类型
Java 中的枚举是一个比较特殊的类型,既具有 class 的特性,又具有自己特殊的特性。定义枚举类型使用 enum 关键字,枚举值一般使用大写字母. 枚举同样可以拥有构造器和变量,但枚举类型的构造器要求必须是 private 类型。这是为了确保枚举的值一定由自己定义,拒绝外界传入。与 class 不同的是,枚举类型的构造器不定义访问权限时,默认为 private。
enum UserType{
STUDENT(28),
EMPLOYEE(30),
WRITER(18);
int age;
UserType(int age){
this.age = age;
}
}
枚举类型自动拥有 values 和 valueOf 方法,values 用于获取枚举所有的值,valueOf 用于根据名称反查枚举值
使用 javap -c class文件反编译
javap -c UserType
反编译结果如下
public final class com.test.entity.UserType extends java.lang.Enum<com.test.entity.UserType> {
public static final com.test.entity.UserType STUDENT;
public static final com.test.entity.UserType EMPLOYEE;
public static final com.test.entity.UserType WRITER;
int age;
public static com.test.entity.UserType[] values();
Code:
0: getstatic #1 // Field $VALUES:[Lcom/test/entity/UserType;
3: invokevirtual #2 // Method "[Lcom/test/entity/UserType;".clone:()Ljava/lang/Object;
6: checkcast #3 // class "[Lcom/test/entity/UserType;"
9: areturn
public static com.test.entity.UserType valueOf(java.lang.String);
Code:
0: ldc #4 // class com/test/entity/UserType
2: aload_0
3: invokestatic #5 // Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
6: checkcast #4 // class com/test/entity/UserType
9: areturn
static {};
Code:
0: new #4 // class com/test/entity/UserType
3: dup
4: ldc #8 // String STUDENT
6: iconst_0
7: bipush 28
9: invokespecial #9 // Method "<init>":(Ljava/lang/String;II)V
12: putstatic #10 // Field STUDENT:Lcom/test/entity/UserType;
15: new #4 // class com/test/entity/UserType
18: dup
19: ldc #11 // String EMPLOYEE
21: iconst_1
22: bipush 30
24: invokespecial #9 // Method "<init>":(Ljava/lang/String;II)V
27: putstatic #12 // Field EMPLOYEE:Lcom/test/entity/UserType;
30: new #4 // class com/test/entity/UserType
33: dup
34: ldc #13 // String WRITER
36: iconst_2
37: bipush 18
39: invokespecial #9 // Method "<init>":(Ljava/lang/String;II)V
42: putstatic #14 // Field WRITER:Lcom/test/entity/UserType;
45: iconst_3
46: anewarray #4 // class com/test/entity/UserType
49: dup
50: iconst_0
51: getstatic #10 // Field STUDENT:Lcom/test/entity/UserType;
54: aastore
55: dup
56: iconst_1
57: getstatic #12 // Field EMPLOYEE:Lcom/test/entity/UserType;
60: aastore
61: dup
62: iconst_2
63: getstatic #14 // Field WRITER:Lcom/test/entity/UserType;
66: aastore
67: putstatic #1 // Field $VALUES:[Lcom/test/entity/UserType;
70: return
}
- UserType 是 final 的
- UserType 继承自 java.lang.Enum 类
- 声明了字段对应的三个个 static final UserType 的实例
- 实现了 values() 和 valueOf(String) 静态方法
- static{} 对所有成员进行初始化
根据字节码反推
public enum UserType extends java.lang.Enum<UserType>{
public static final UserType STUDENT;
public static final UserType EMPLOYEE;
public static final UserType WRITER;
int i;
private static final UserType[] $VALUES;
public static UserType[] values() {
return $VALUE.clone();
}
public static UserType valueOf(String name) {
return Enum.valueOf(UserType.class, name);
}
private UserType(String name, int original) {
super(name, original)
}
static {
STUDENT = new UserType("STUDENT",0, 28);
EMPLOYEE = new UserType("EMPLOYEE",1, 30);
WRITER = new UserType("WRITER",2, 18);
$VALUES = new Gender[] {STUDENT, EMPLOYEE,WRITER};
}
private UserType(String s ,int i,int age) {
super(s,i);
this.age = age;
}
}
由于上面的那个类是无法被编译的,因为 Java 编译器限制了我们显式的继承自 java.Lang.Enum 类,所以我们使用第三方工具反编译出来如下
public enum UserType {
STUDENT(28),
EMPLOYEE(30),
WRITER(18);
int age;
// $FF: synthetic field
private static final UserType[] $VALUES = new UserType[]{STUDENT, EMPLOYEE, WRITER};
private UserType(int age) {
this.age = age;
}
}
JDK1.8 Enum抽象类源码
/*
* Copyright (c) 2003, 2011, 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.
*
* 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™ 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;
/**
* 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");
}
}
UserType 编译后变成了一个普通的 class UserType 拥有修饰符 final,因此不能有子类。同时继承了 Enum 类型,因此开发中 UserType 也将不能继承任何父类。
自动生成的 values 和 valueOf Java 编译枚举类型时,自动加上两个静态方法 values 和 valueOf。如果我们定义了签名完全相同的方法会编译报错 “已在枚举中定义了方法 values”
枚举类型使用私有静态变量 $VALUES 存储所有的值,在静态初始化中赋值,类型为数组,值为所有枚举值,用于 values 和 valueOf 方法
values 方法的作用是返回所有枚举值,实现很简单,就是 clone 一下 $VALUES 的值。valueOf 方法的作用是根据枚举值的名称返回枚举值,实现方法是调用 Enum.valueOf 方法,后文会在 Enum 类型中介绍这个方法。
Enum 类型是 Java 中所有枚举类型的父类,并且是抽象类。需要注意的是我们不能直接继承 Enum 类,只有编译器生成的枚举最终的 class 可以继承,直接继承会导致编译器报错 “类无法直接扩展 java.lang.Enum”
Enum 类型提供了我们常用的 name() 和 ordinal() 方法,其中的 name 和 ordinal 变量都是 final 类型。
Enum 拥有一个构造器,参数为 name 和 ordinal。经过前面的分析可以知道,这个构造器我们是没有办法直接调用的,只有编译器编译的枚举类型可以调用。
枚举最终编译成 class,因此也可以实现接口
public enum UserType extends Enum implements Runnable{
STUDENT(28),
EMPLOYEE(30),
WRITER(18);
int age;
UserType(int age) {
this.age = age;
}
@Override
public void run() {
System.out.println("枚举实现接口");
}
EnumMap 是一个使用枚举值做 key 的 Map 实现。如下代码即可创建 EnumMap 的实例,创建时需要指定 key 类型的 class,或者传入一个 map 进行初始化。EnumMap 使用数组存储数据,效率高于 HashMap。
public void test(){
EnumMap<UserType,String> map = new EnumMap<UserType, String>(UserType.class);
map.put(UserType.EMPLOYEE,"测试");
System.out.println(map.get(UserType.EMPLOYEE));
}
EnumSet 是一个枚举集合,是一个抽象类,它有两个继承类:JumboEnumSet和 RegularEnumSet。EnumSet 使用 bit 位存储数据,效率高于 HashSet,同样地,EnumSet 的容量也不能发生变化,枚举类型的定义决定了 EnumSet 的固定容量值。
public void test(){
//set中包含这个枚举类型所有元素
EnumSet<UserType> set = EnumSet.allOf(UserType.class);
//set为空但是指定枚举类型的set
EnumSet<UserType> set2 = EnumSet.noneOf(UserType.class);
//set中只能包含指定的枚举值
EnumSet<UserType> set1 = EnumSet.range(UserType.EMPLOYEE,UserType.STUDENT);
//添加枚举类型
set2.add(UserType.EMPLOYEE);
//复制一个set
EnumSet<UserType> set3 = EnumSet.copyOf(set1);
}