简体   繁体   English

如何将空字符串设置为 Java 枚举值?

[英]How to set empty string as Java enum value?

I am facing a problem when handling with empty java string as java enum value.将空 java 字符串作为 java 枚举值处理时,我遇到了问题。 Its throwing IllegalArgumentException when reading the "" data.它在读取“”数据时抛出 IllegalArgumentException。

updateType = records.get(11);
UpdateMethodType updateMethod = null;
String empty = "";
if (updateType != null || !updateType.isEmpty()) {
    System.out.println("Update type ----->" + updateType);
    updateMethod = KalturaUpdateMethodType.valueOf(updateType);
} else {
    updateMethod = KalturaUpdateMethodType.valueOf(empty);
}

Please help me resolving this.请帮我解决这个问题。

There can't be any empty enum value.不能有任何空的枚举值。 you can instead have a special enum value named EMPTY in KalturaUpdateMethodType .您可以在KalturaUpdateMethodType名为 EMPTY 的特殊枚举值。

This is an expected behavior.这是预期的行为。 You should not pass empty string to valueOf() method.您不应将空字符串传递给valueOf()方法。 and if you pass null you will get a NPE.如果你通过 null 你会得到一个 NPE。 So better you create a new enum for EMPTY string.所以最好为 EMPTY 字符串创建一个新的枚举。 Like :喜欢 :

enum KalturaUpdateMethodType {
    EMPTY("");
    String value;
    private KalturaUpdateMethodType(String value) {
      this.value = value;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM