if-statement - 如果不使用语句
问题描述
我在 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 语句由于某种原因未执行。
解决方案
推荐阅读
- javascript - 在javascript类中调用类方法
- google-bigquery - 在聚类时使用基于摄取时间的伪字段 (_PARTITIONTIME) 作为分区
- php - 如何在 laravel 中自动填充字段?
- excel - 超链接到同一工作表中的特定单元格
- oracle - 错误 - pl/sql developer -12154 tns 无法解析指定的连接标识符
- sql - 将单个逗号分隔的行转换为多行
- mysql - 如何将多值属性添加到 mysql 工作台?
- php - 如何在 Yii2 活动表单中的每个下拉列表项之前和之后附加“HTML 标签”
- javascript - 当我在假期数组中有更多值时,JS 函数进入无限循环
- javascript - Nextjs 向组件发送数据(页面标题)