在我使用它的数据库中,有一些我想映射到 State
枚举的魔数(Magic Number),反之亦然。我对 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)));
但我会对任何和所有替代方案感兴趣。
最佳答案
我删除了无用的静态 block 并改进了逆函数。
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 开始的序数,则可以省略构造函数参数、私有(private) int code 和映射,如下所示:
int2state.put( this.ordinal(), this );
关于java - 将魔数(Magic Number)映射到枚举值,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24604892/