发布于 

Java 枚举的本质

概要

本文跟大家一起探讨一下 Java 枚举的本质,这篇文章的内容是我在 2012年09月05日 发布到 CSDN 上面的一篇博文 Java 枚举:理解枚举本质,虽然已经不在 CSDN 上面耕耘了,但偶尔也会去看看朋友们的留言,毕竟感情在那里!今天偶然看到有小伙伴评论这篇文章,一时兴起就想再次分享给大家。

1

学习编程语言,会用只是最基本的要求,了解和熟悉其实现、运行机制才使得你有别于常人!

C 枚举

在 C 语言中,可以这样来定义枚举,如下示例:

1
2
3
enum color {
RED=0, GREEN, BLUE, YELLOW
} col;

关键字 enum 定义枚举,在定义枚举的同时,声明该枚举变量 col.

注意:C 语言中枚举成员的值是根据上下文自动加 1 的(GREEN = 1,BLUE = 2 等)。

C 语言中 switch 语句支持枚举类型,如下示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<stdio.h>

int main()
{
enum color {
RED=0, GREEN, BLUE, YELLOW
} col;

int cl;

printf("0=red, 1=green, 2=blue, 3=yellow. seclect:\n");

scanf("%d",&cl);

col=(enum color) cl;

switch(col) {
case RED:
printf("the color is red\n");
break;
case GREEN:
printf("the color is green\n");
break;
case BLUE:
printf("the color is blue\n");
break;
case YELLOW:
printf("the color is yellow\n");
break;
defalut:
printf("no this color\n");
break;
}

return 0;
}

Java 枚举

那么,Java 里面的枚举与其类似,但是又不是完全一样。Java 语言中定义枚举也是使用 enum 关键字,如下示例是 Java 语言的枚举:

1
2
3
public enum Color {
RED, GREEN, BLUE, YELLOW;
}

上述定义了一个枚举类型 Color(可以说是类,编译之后是 Color.class).

上面的定义,还可以改成下面的这种形式:

1
2
3
public enum Color {
RED(), GREEN(), BLUE(), YELLOW();
}

到这里你可能会觉得迷茫(如果你是初学者的话),为什么这样子也可以,why?

其实,枚举的成员就是枚举对象,只不过它们是静态常量而已。

使用 javap 命令(javap 文件名<没有后缀.class>)可以反编译 class 文件,如下:
​​​​1

我们可以使用普通类来模拟枚举,下面定义一个 Color 类,如下:

1
2
3
4
5
6
public class Color {
private static final Color RED = new Color();
private static final Color GREEN = new Color();
private static final Color BLUE = new Color();
private static final Color YELLOW = new Color();
}

结合上图反编译的结果,做一下对比,你是否看出了一点端倪(坏笑),如果没有看出来,那就接着往下看吧。

如果按照这个逻辑,是否还可以为其添加另外的构造方法?答案是肯定的!

1
2
3
4
5
6
7
8
9
10
11
12
public enum Color {
RED("red color", 0), GREEN("green color", 1),
BLUE("blue color", 2), YELLOW("yellow color", 3);

Color(String name, int id) {
_name = name;
_id = id;
}

String _name;
int _id;
}

Color 声明了两个成员变量,并为其构造带参数的构造器。

如果你这样创建一个枚举:

1
2
3
4
public enum Color {
RED("red color", 0), GREEN("green color", 1),
BLUE("blue color", 2), YELLOW("yellow color", 3);
}

编译器就会报错:

1
The constructor EnumDemo.Color(String, int) is undefined

到此,你应该看明白了,枚举和普通的 Java 类很像。

对于类来讲,最好将其成员变量私有化,并且为成员变量提供 getset 方法。

按照这个原则,可以进一步写好 enum Color,如下示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public enum Color {
RED("red color", 0), GREEN("green color", 1),
BLUE("blue color", 2), YELLOW("yellow color", 3);

Color(String name, int id) {
_name = name;
_id = id;
}

private String _name;
private int _id;

public void setName(String name) {
_name = name;
}

public void setId(int id) {
_id = id;
}

public String getName() {
return _name;
}

public int getId() {
return _id;
}
}

但是 Java 设计枚举的目的是提供一组常量,方便开发者使用。如果我们冒然的提供 set 方法(外界可以改变其成员属性),好像有点违背了设计的初衷。

那么,我们应该舍弃 set 方法,保留 get 方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public enum Color {
RED("red color", 0), GREEN("green color", 1),
BLUE("blue color", 2), YELLOW("yellow color", 3);

Color(String name, int id) {
_name = name;
_id = id;
}

private String _name;
private int _id;

public String getName() {
return _name;
}

public int getId() {
return _id;
}
}

对于普通的基本类可以将其实例化,那么,能否实例化枚举呢?

在回答这个问题之前,先来看看 Color.class 文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static enum Color {
RED("red color", 0), GREEN("green color", 1),
BLUE("blue color", 2), YELLOW("yellow color", 3);

private String _name;
private int _id;

private Color(String name, int id) {
this._name = name;
this._id = id;
}

public String getName() {
return this._name;
}

public int getId() {
return this._id;
}
}

可以看出,编译器淘气的为其构造方法加上了 private,那么也就是说,我们无法实例化枚举。

所有枚举类都继承了 Enum 类的方法,包括 toStringequalshashcode 等方法。因为 equalshashcode 方法是 final 的,所以不可以被枚举重写(只可以继承),但可以重写 toString 方法。

文末的附录中提供了 Enum 的源码,有兴趣可以查看阅读!

那么,使用 Java 的类来模拟一下枚举,大概是这个样子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package mark.demo;

import java.util.ArrayList;
import java.util.List;

public class Color {
private static final Color RED = new Color("red color", 0);
private static final Color GREEN = new Color("green color", 1);
private static final Color BLUE = new Color("blue color", 2);
private static final Color YELLOW = new Color("yellow color", 3);

private final String _name;
private final int _id;

private Color(String name, int id) {
_name = name;
_id = id;
}

public String getName() {
return _name;
}

public int getId() {
return _id;
}

public static List<Color> values() {
List<Color> list = new ArrayList<Color>();
list.add(RED);
list.add(GREEN);
list.add(BLUE);
list.add(YELLOW);
return list;
}

@Override
public String toString() {
return "the color _name=" + _name + ", _id=" + _id;
}
}

附录

Enum.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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() { }
}

扫码关注,你我就各多一个朋友~


本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。

veryitman