[英]How do I check a string is empty or null using if statement in Java?
I need to get the enum itself first by using RegoDocumentType.getByValue(createOrderRequest.getIdDocument().getIdType())
我需要首先使用
RegoDocumentType.getByValue(createOrderRequest.getIdDocument().getIdType())
获取枚举本身
Then check for null value, if it is not null, it will return the enum value.然后检查 null 的值,如果不是 null,则返回枚举值。 Else, it will return the
createOrderRequest.getIdDocument().getIdType()
as default.否则,它将默认返回
createOrderRequest.getIdDocument().getIdType()
。
So how do I refactor the code to only use one if statement to cater for both NRIC/11B and FIN smag value to rego value using RegoDocumentType enum?那么,如何使用 RegoDocumentType 枚举重构代码以仅使用一个 if 语句来满足 NRIC/11B 和 FIN smag 值到 rego 值?
Here's my enum:这是我的枚举:
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
}
or或者
String something = "";
return something == null || something.isEmpty() ? [value A] : [value B];
createOrderRequest.getIdDocument().getIdType()
seems to be a String in you case. createOrderRequest.getIdDocument().getIdType()
在你的情况下似乎是一个字符串。 You cannot return a string from getBySmagValue
.您不能从
getBySmagValue
返回字符串。 Consider returning null or throwing an exception instead:考虑返回 null 或抛出异常:
public static RegoDocumentType getBySmagValue(String smagValue) {
if (smagValue == null) reutrn null;
return BY_SMAG_VALUE.get(smagValue.toLowerCase());
}
or或者
public static RegoDocumentType getBySmagValue(String smagValue) {
if (smagValue == null) throw new IllegalStateException();
return BY_SMAG_VALUE.get(smagValue.toLowerCase());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.