Groovy在检查JsonNode对象是否为null时跳过它们,即使它们不是null

Groovy在检查JsonNode对象是否为null时跳过它们,即使它们不是null,groovy,Groovy,为什么Groovy跳过这个if语句 public static void main(String[] args) { JsonNode jsonNode = JsonNodeFactory.instance.objectNode() if (jsonNode) { println 'It works' //doesn't print it } } 显式检查null效果良好: public static void main(String[] args) {

为什么Groovy跳过这个if语句

public static void main(String[] args) {
    JsonNode jsonNode = JsonNodeFactory.instance.objectNode()
    if (jsonNode) {
        println 'It works' //doesn't print it
    }
}
显式检查null效果良好:

public static void main(String[] args) {
    JsonNode jsonNode = JsonNodeFactory.instance.objectNode()
    if (jsonNode != null) {
        println 'It works' //works well
    }
}
进口:

import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.JsonNodeFactory
import com.fasterxml.jackson.databind.node.ObjectNode

如果我在Intellij中使用断点,它也可以工作。

它取决于Groovy ObjectasBoolean。 默认情况下,如果对象为null,则返回false

将对象实例强制为布尔值。对象被强制为 如果不为null,则为true;如果为null,则为false

当存在这样的检查时,Groovy尝试使用asBoolean将对象强制转换为boolean。 这个例子表明:

public static void main(String[] args) {
    AsBoolFalse asBoolFalse = new AsBoolFalse()
    if (asBoolFalse) {
        println 'AsBoolFalse doesn\'t work' //doesn't print it
    }

    AsBoolTrue asBoolTrue = new AsBoolTrue()
    if (asBoolTrue) {
        println 'AsBoolTrue works' //works well
    }
}

static class AsBoolFalse {
    public boolean asBoolean() {
        return false
    }
}

static class AsBoolTrue {
    public boolean asBoolean() {
        return true
    }
}

JsonNode重写asBoolean以返回false,因此我们需要显式检查null。

我不明白。你们都在24分钟前问了又回答了这个问题?很好。我在写这个问题的时候找到了答案。所以我决定不跳过这个问题继续回答。也许它会对某些人有用。有两天我都不清楚为什么我会有这样的行为。