首页 > 解决方案 > 如果不使用语句

问题描述

我在 Groovy 中有以下代码:

seedGerritHost = config.seedgerrit?.host
println "seedGerritHost: " + seedGerritHost
if (seedGerritHost == null) {
    seedGerritHost = config.gerrit.host.toString()
    print "seedGerritHost was null, now its: " + seedGerritHost
}
...
def predefineJobs = new File("/usr/share/jenkins/predefineJobs")
def newPredefineJobs = predefineJobs.text
    .replace("#projectName",config.jenkins.project.toString())
    .replace("#gerritHost",seedGerritHost.toString())

对象config.seedgerrit?.host未定义,因此我假设必须执行 if 语句,但事实并非如此。

日志中抛出空指针异常:

seedGerritHost: null
seedGerritPort: null
2020-02-14 18:29:28.381+0000 [id=25]    WARNING j.util.groovy.GroovyHookScript#execute: 
Failed to run script file:/var/jenkins_home/init.groovy.d/04.jobs.groovy
java.lang.NullPointerException
    at java.lang.String.replace(String.java:2240)
    at java_lang_String$replace$0.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at 04_jobs.run(04.jobs.groovy:27)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:585)
    at jenkins.util.groovy.GroovyHookScript.execute(GroovyHookScript.java:136)
    at jenkins.util.groovy.GroovyHookScript.execute(GroovyHookScript.java:127)
    at jenkins.util.groovy.GroovyHookScript.run(GroovyHookScript.java:110)
    at hudson.init.impl.GroovyInitScript.init(GroovyInitScript.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at hudson.init.TaskMethodFinder.invoke(TaskMethodFinder.java:104)
    at hudson.init.TaskMethodFinder$TaskImpl.run(TaskMethodFinder.java:175)
    at org.jvnet.hudson.reactor.Reactor.runTask(Reactor.java:296)
    at jenkins.model.Jenkins$5.runTask(Jenkins.java:1119)
    at org.jvnet.hudson.reactor.Reactor$2.run(Reactor.java:214)
    at org.jvnet.hudson.reactor.Reactor$Node.run(Reactor.java:117)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

空指针异常与.replace("#gerritHost",seedGerritHost)行有关。seedGerritHost为空,因为 if 语句由于某种原因未执行。

标签: if-statementgroovynullpointerexception

解决方案


推荐阅读