在数据库中,我使用这个,有我想映射到State
enum的神奇数字,反之亦然。我对undefined.code = 0
的静态声明很感兴趣。如果这是声明的话,它实际上是做什么的?
package net.bounceme.dur.data;
public enum State {
undefined(0), x(1), o(2), c(3), a(4), l(5), d(6);
private int code = 0;
static {
undefined.code = 0;
x.code = 1;
o.code = 2;
c.code = 3;
a.code = 4;
l.code = 5;
d.code = 6;
}
State(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
public static State getState(int code) {
for (State state : State.values()) {
if (state.getCode() == code) {
return state;
}
}
return undefined;
}
}
当前,枚举工厂方法的用法如下:
title.setState(State.getState(resultSet.getInt(5)));
我删除了无用的静态块并改进了逆函数。
public enum State {
private static Map<Integer,State> int2state = new HashMap<>();
undefined(0), x(1), o(2), c(3), a(4), l(5), d(6);
private int code;
State(int code) { // executed for *each* enum constant
this.code = code;
int2state.put( code, this );
}
public int getCode() {
return this.code;
}
public static State getState(int code) {
return int2state.get(code);
}
}
如果"code"整数肯定是从0开始的序数,则可以省略Constructor形参、私有int code并像这样映射:
int2state.put( this.ordinal(), this );
在你发布的代码中,静态块行
undefined.code = 0;
访问枚举常量undefined
,将可变字段code
的值从0
盲目设置为0
。这里定义了常量
undefined(0)
,代码为0
。同样x
和1
。等等
它实际上做了与构造函数相同的事情-设置与每个enum值相关的code
。
在您的示例中,static { ... }
块是多余的(不必要的),可能应该删除,因为它重复了以underfined(0)
开头的行。
Enum
的使用变得棘手的地方是查找(在您的例子中是getState(...)
方法)。这里的case
语句确实第三次重复了代码,您可能更好地构建一个Map
,它接受代码(int
)并返回enum (State
) -只需谷歌一下,有很多关于如何做到这一点的例子。
只是一个提示。将您的getState(int)
方法更改为
public static State getState(int code) {
for (State state : State.values()) {
if (state.getCode() == code) {
return state;
}
}
return undefined;
}