如何使用 Java 中的 if 语句检查字符串是空还是空?

问题描述

我需要首先使用 RegoDocumentType.getByValue(createOrderRequest.getIdDocument().getIdType())

获取枚举本身

然后检查空值,如果不为空,则返回枚举值。否则,它将返回 createOrderRequest.getIdDocument().getIdType() 作为默认值。

那么,我如何重构代码以仅使用一个 if 语句来满足 NRIC/11B 和 FIN smag 值以使用 RegoDocumentType 枚举的 rego 值?

这是我的枚举:

public enum RegoDocumentType {
    
    NRIC_11B("NRIC/11B",IdentityType.NRIC.toValue()),FIN("Employment Pass",IdentityType.EM_PASS.toValue()),;
    private static final Map<String,RegoDocumentType> BY_SMAG_VALUE = new HashMap<>();
    static {
        for (RegoDocumentType identityType : values()) {
            BY_SMAG_VALUE.put(identityType.getSmagValue().toLowerCase(),identityType);
        }
    }
    private final String smagValue;
    private final String regoValue;
    RegoDocumentType(String smagValue,String regoValue) {
        this.smagValue = smagValue;
        this.regoValue = regoValue;
    }
    public String getSmagValue() {
        return smagValue;
    }
    public String getRegoValue() {
        return regoValue;
    }
    public static RegoDocumentType getBySmagValue(String smagValue)
    { return BY_SMAG_VALUE.get(smagValue.toLowerCase()); }
}

解决方法

    String something = "";
    if(something == null || something.isEmpty()) {
        // return A
    } else {
        // return B
    }

    String something = "";
    return something == null || something.isEmpty() ? [value A] : [value B];
,

createOrderRequest.getIdDocument().getIdType() 在你的情况下似乎是一个字符串。您不能从 getBySmagValue 返回字符串。考虑返回 null 或抛出异常:

public static RegoDocumentType getBySmagValue(String smagValue) { 
    if (smagValue == null) reutrn null;
    return BY_SMAG_VALUE.get(smagValue.toLowerCase()); 
}

public static RegoDocumentType getBySmagValue(String smagValue) { 
    if (smagValue == null) throw new IllegalStateException();
    return BY_SMAG_VALUE.get(smagValue.toLowerCase()); 
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...