Java 将幻数映射到枚举值,反之亦然
在数据库中,我正在使用它,其中有一些我想映射到状态枚举的幻数,反之亦然。我对undefined.code=0的静态声明很感兴趣。这个声明,如果是这样的话,实际上是做什么的Java 将幻数映射到枚举值,反之亦然,java,enums,magic-numbers,Java,Enums,Magic Numbers,在数据库中,我正在使用它,其中有一些我想映射到状态枚举的幻数,反之亦然。我对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
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)));
但是我对任何和所有的替代方案都感兴趣。在您发布的代码中,静态块行
undefined.code = 0;
它访问未定义的枚举常量,并将可变字段代码的值从0盲目设置为0。基本上,常数是在这里定义的
undefined(0)
代码为0。x和1也是如此。依此类推。它确实与构造函数做了相同的事情——设置与每个枚举值关联的代码 在您的示例中,静态{…}块是多余的,可能应该删除,因为它复制了从underfined0开始的行
枚举使用变得棘手的一点是在您的案例中的查找getState。。。方法这里的case语句确实第三次复制了代码,您最好构建一个映射,该映射接受代码int并返回枚举状态-只需谷歌搜索一下,就有很多关于如何执行此操作的示例。我删除了无用的静态块并改进了反向函数
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);
}
}
只是一个提示。将getStateint方法更改为
public static State getState(int code) {
for (State state : State.values()) {
if (state.getCode() == code) {
return state;
}
}
return undefined;
}
你为什么要这样做?只需更改私有int code=0;到私有的最终整数代码;分配一次。静态块的意义是什么?将枚举视为具有保证单例属性的常规对象可能会有所帮助。所以代码只是状态对象的一个字段,未定义。代码是为状态对象的一个特定实例访问该字段。@ElliottFrisch我不知道静态块的意义是什么,这是我要问的一部分。它被用在一个和我类似的问题中,并且似乎…赋值?静态块没有任何用途。它做的和构造函数已经做的一样。@Iaune对getStateint的回答实际上更快更好。映射是如何填充的?我必须把它打印出来才能看到,但在我看来,地图上只有一个条目。它是如何拥有所有映射项的?请参阅我对构造函数的第二条编辑注释。对于每个枚举值执行一次。构造函数被调用多次,每个枚举实例调用一次。因此,地图已完全填充。你应该接受这个答案,它是正确和有效的。
public static State getState(int code) {
for (State state : State.values()) {
if (state.getCode() == code) {
return state;
}
}
return undefined;
}