是否有更简洁的写作方式
if (myInteger != null && myInteger != 0) { ... }
Run Code Online (Sandbox Code Playgroud)
例如,对于Strings,您可以使用StringUtils.isBlank()
Flo*_*cht 14
使用Java 8:
if (Optional.ofNullable(myInteger).orElse(0) != 0) {
...
}
Run Code Online (Sandbox Code Playgroud)
请注意Optional,根据您的使用情况,可以帮助您完全避免if条件...
由于StringUtils问题中提到了类,我假设项目中已经使用了 Apache Commons lib。
然后您可以使用以下内容:
if (0 != ObjectUtils.defaultIfNull(myInteger, 0)) { ... }
Run Code Online (Sandbox Code Playgroud)
或者使用静态导入:
if (0 != defaultIfNull(myInteger, 0)) { ... }
Run Code Online (Sandbox Code Playgroud)
我将为此使用三元条件。就像是 :
public static boolean isNullorZero(Integer i){
return 0 == ( i == null ? 0 : i);
}
Run Code Online (Sandbox Code Playgroud)
我同意这不可读;)
| 归档时间: |
|
| 查看次数: |
33925 次 |
| 最近记录: |