折腾:
【未解决】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
试试:
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中如何枚举的值返回对应枚举变量本身