Groovy从ProjectComponent集合查找对象报错:MissingPropertyException
修复Jira自动化Groovy脚本的MissingPropertyException错误
错误原因
你原代码的问题很明确:anyMatch闭包内的it是局部变量,只能在闭包的大括号范围内使用。你在if代码块里直接引用it,相当于在当前类的作用域里找名为it的属性,自然会报找不到的错误。而且anyMatch仅返回布尔值,根本没法帮你拿到匹配的组件对象。
正确写法
推荐两种更合适的实现方式:
方式1:用Groovy集合原生find方法(最简洁)
Groovy对集合有原生扩展,不用写Stream API就能直接查找匹配元素:
// 直接找到匹配名称的组件,找不到则返回null newComponent = newIssueproject.getComponents().find { it.getName().equals(shortenedComponentName) } // 可选:如果需要判断是否找到的话 if (newComponent) { // 这里处理找到组件后的逻辑 }
方式2:用Java Stream API的filter+findFirst
如果习惯用Stream写法,也可以这样实现:
Optional<ProjectComponent> matchedComponent = newIssueproject.getComponents().stream() .filter { it.getName().equals(shortenedComponentName) } .findFirst() if (matchedComponent.isPresent()) { newComponent = matchedComponent.get() }
内容的提问来源于stack exchange,提问作者منى
相关产品推荐
相关产品推荐

