获取枚举字符串

时间:2017-10-22 09:57:54

标签: java enums

我有以下枚举:

 public static enum OpCode {
    a((byte) 0x0),
    b((byte)0x18),
    c((byte)0x1A);

    private byte value; 

    private  OpCode (byte value) {
        this.value = value;
    }

    byte getValue() {
        return value;
    }

如果我的值为x = 0x18 我怎样才能得到字符串' b'?

这是我试过的:

    System.out.println(OpCode.values()[x]);

但它不起作用

3 个答案:

答案 0 :(得分:6)

您可以实现静态方法,例如fromByte

public enum OpCode {
... truncated
    public static OpCode fromByte(byte x) {
        for(OpCode oc : values()) {
           if (oc.getValue() == x) {
               return oc;
           }
        }
        throw new IllegalArgumentException("Unknown OpCode value: " + x);
    }
}

然后你可以这样称呼它:

OpCode oc = OpCode.fromByte(x);

答案 1 :(得分:4)

Joe C在其评论中建议进行线性搜索,或使用MapOpCode存储Byte value个实例。

 public static enum OpCode {

    a((byte) 0x0),
    b((byte)0x18),
    c((byte)0x1A);

    private final byte value;

    private final static Map<Byte, OpCode> opCodesByByte;

    static {
          opCodesByByte = new HashMap<>();
          for (OpCode opCode : values()) {
             opCodesByByte.put(opCode.value, opCode);   
          }
    }

   ...    
  }

并在static中添加OpCode方法以提供搜索方法:

public static OpCode of(byte value){
   return opCodesByByte.get(value);
}

请注意,在此实现中,如果没有匹配,则返回null

答案 2 :(得分:0)

你需要循环枚举:

    private static Map<Byte, OpCode> valueToOpCode = new HashMap<>();

    static OpCode getOpCode(byte value) {
        return valueToOpCode.get(value);
    }

    public static enum OpCode {
        a((byte) 0x0),
        b((byte)0x18),
        c((byte)0x1A);            

        private byte value; 

        private  OpCode(byte value) {
            this.value = value;
            valueToOpCode.put(value, this);
        }

        byte getValue() {
            return value;
        }

    }

    private void test() {            
        byte x = 0x18;
        System.out.println(getOpCode(x)); // prints 'b'             
    }

或者,建立一个这样的地图:

     // As fields inside curly braces can contain special characters
     // using /\{[^}]+\}/g as regex 
     // As dynamic URL won't contain special chars replacing it with (\w+)
     // Using () to group the dynamic fields

     var regexUrl = docUrl.replace(/\{[^}]+\}/g, "(\\w+)");
     regexUrl = "^" + regexUrl + "$";
     var res = dynUrl.match(regexUrl);
相关问题