我想知道在java中是否有可能if-else像python一样评估多个变量.
实际代码
if(abc!=null && xyz!=null)
{//...}
Run Code Online (Sandbox Code Playgroud)
虚拟代码
if(abc && xyz !=null)
{// will it be possible}
Run Code Online (Sandbox Code Playgroud)
jto*_*szk 16
第一稿
你可以写这样的smth:
boolean notNull(Object item) {
return item != null;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用它像:
if (notNull(abc) && notNull(xyz)) {
//...
}
Run Code Online (Sandbox Code Playgroud)
更新1:
我提出了一个新想法,使用varargs编写函数,如:
boolean notNull(Object... args) {
for (Object arg : args) {
if (arg == null) {
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
用法:(你可以传递给多个参数的函数)
if (notNull(abc, xyz)) {
//...
}
Run Code Online (Sandbox Code Playgroud)
更新2:
最好的方法是使用库apache commons ObjectUtils,它包含几个随时可用的方法,如: