Groovy中如何实现Project属性的安全解引用以规避异常
Gradle Project属性安全解引用方案
你可以根据你的Gradle版本和使用场景选择以下三种方案:
方案一:使用
hasProperty()先校验属性存在性(全版本兼容)
Gradle Project原生提供hasProperty()方法专门用于判断属性是否存在,校验通过后再取值即可避免未知属性报错,示例代码如下:// 属性存在则取值,不存在直接返回null def junkValue = project.hasProperty('junk') ? project.junk : null // 嵌套属性场景可搭配安全导航操作符避免空指针 def nestedValue = project.hasProperty('outerProp') ? project.outerProp?.innerProp : null方案二:使用
findProperty()直接取值(Gradle 3.0+版本适用)
高版本Gradle提供更简洁的findProperty()API,属性不存在时会直接返回null,不会抛出异常:// 直接取值,不存在返回null def junkValue = project.findProperty('junk') // 配合Elvis操作符可直接设置默认值 def junkValueWithDefault = project.findProperty('junk') ?: '默认值' // 嵌套属性场景搭配安全导航使用 def nestedValue = project.findProperty('outerProp')?.innerProp方案三:通过属性Map集合取值(全Groovy语法兼容)
Project的properties属性是存储所有配置属性的Map集合,访问Map不存在的key只会返回null不会报错:def junkValue = project.properties['junk'] // 嵌套属性示例 def nestedValue = project.properties['outerProp']?.innerProp
提示:上述三种方案都覆盖了「属性未定义」和「属性值为null」两种异常场景,比单独使用安全导航操作符的适配范围更全面,生产环境建议优先使用。
内容的提问来源于stack exchange,提问作者Bazer Con
相关产品推荐
相关产品推荐

