在if条件下一起评估多个变量

agp*_*gpt 6 java if-statement

我想知道在java中是否有可能if-elsepython一样评估多个变量.

实际代码

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,它包含几个随时可用的方法,如:


Gen*_* S. 7

唯一可行的方法是if abc是一个布尔值(并且它不会做你希望它会做的事情,它只会测试abc == true).在Java中无法将一件事与多件事进行比较.