最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Java中如何枚举的值返回对应枚举变量本身

Java crifan 989浏览 0评论
折腾:
【未解决】java的com.iec.analysis.解析104出错:类型标识出错,无法解析信息对象
期间,对于代码:
builder.append("类属性标识符[7 byte]:").append(TypeIdentifier.getDescribe(asdu[0])).append("\n");
希望变成:
目前的getDescribe
...
public enum TypeIdentifier {
    M_SP_NA_1(1, "0x01", "Single-point information"),
    M_SP_TA_1(2, "0x02", "Single-point information with time tag"),
...
    F_DR_TA_1(126, "0x7E", "Directory");


    private int code;
    private String hexStr;
    private String describe;


    TypeIdentifier(int code, String hexStr, String describe) {
        this.code = code;
        this.hexStr = hexStr;
        this.describe = describe;
    }


    public static String getDescribe(int code) throws UnknownTypeIdentifierException {
        for (TypeIdentifier value : TypeIdentifier.values()) {
            if (value.code == code) {
                // String idDesc = value.hexStr + " " + value.describe;
                String idDesc = String.format("%s %s", value.hexStr, value.describe);
                return idDesc;
            }
        }


        throw new UnknownTypeIdentifierException(code);
    }
}

此处想要改造成:
直接从枚举的值,即code,解析返回出对应的枚举变量:
java  from value get enum
How to get an enum value from a string value in Java? – Stack Overflow
Getting String value from enum in Java – Stack Overflow
Attaching Values to Java Enum | Baeldung
How can I lookup a Java enum from its String value? – Stack Overflow
java – get enum name from enum value – Stack Overflow
试试:
    public static TypeIdentifier fromCode(int code){
        for(TypeIdentifier curValue : TypeIdentifier.values()){
            if(code == curValue.code) {
                return curValue;
            }
        }


        return null;
    }
然后就可以了:
【总结】
此处给enum弄个函数,比如叫fromCode,然后内部用到.values()去匹配,返回对应的enum变量。
完整代码:
public enum TypeIdentifier {
    M_SP_NA_1(1, "0x01", "Single-point information"),
    M_SP_TA_1(2, "0x02", "Single-point information with time tag"),
...
    F_DR_TA_1(126, "0x7E", "Directory");


    private int code;
    private String hexStr;
    private String describe;


    TypeIdentifier(int code, String hexStr, String describe) {
        this.code = code;
        this.hexStr = hexStr;
        this.describe = describe;
    }


    public static TypeIdentifier fromCode(int code){
        for(TypeIdentifier curValue : TypeIdentifier.values()){
            if(code == curValue.code) {
                return curValue;
            }
        }


        return null;
    }
...
}
然后调用时:
    private TypeIdentifier typeId;
...

    public static String ASDU_analysis(int[] asdu) throws xxx {
        ASDU curAsdu = new ASDU();
        curAsdu.typeId = TypeIdentifier.fromCode(asdu[0]);
        // return curAsdu;
即可。

转载请注明:在路上 » 【已解决】Java中如何枚举的值返回对应枚举变量本身

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
89 queries in 0.200 seconds, using 20.15MB memory