java - 将魔数(Magic Number)映射到枚举值,反之亦然

标签 java enums magic-numbers

在我使用它的数据库中,有一些我想映射到 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/

相关文章:

java - 出现错误 com.jnetdirect.jsql.JSQLException : Invalid parameter index:2 Valid range is 1 to 1 While inserting in to database?

java - 一个对象拥有另一个对象

Java 开启枚举值

java - Web服务仅限于单线程?

java - servlet 发生异常时如何重定向到错误页面?

c# - 标志和 << 对枚举的操作? C#

java - 如何在 switch case 中使用枚举类

linux - 为什么ELF magic number中没有16位信息?

通过检查 C 中的魔数(Magic Number)来检查可执行文件或 shell 文件是否有效

c - 为内存数据结构寻找安全的魔数(Magic Number)