【发布时间】:2014-07-07 07:14:04
【问题描述】:
在我使用它的数据库中,有一些我想映射到State 枚举的幻数,反之亦然。我对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)));
但我会对任何和所有替代方案都感兴趣。
【问题讨论】:
-
你为什么要这样做?只需将
private int code = 0;更改为private final int code;并分配一次。static块的意义何在? -
将
enums 视为具有保证单例属性的常规对象可能会有所帮助。所以code只是State对象的一个字段,undefined.code正在访问State对象的特定实例的该字段。 -
@ElliottFrisch 我不知道静态块的意义是什么,这是我要问的一部分。它用于与我的类似问题中,并且似乎...分配值?
-
静态块没有任何用途。它做了构造函数已经做的事情。
标签: java enums magic-numbers