使用GroovyShell.evaluate时如何跳过MissingPropertyException且无需自定义类
GroovyShell.evaluate 跳过 MissingPropertyException 的无自定义类实现方案
以下两种方案均不需要自定义类,也不需要依赖 Expando 即可实现需求:
方案1:重写 Binding 实例的 getVariable 方法
直接在创建的 Binding 实例上重写获取变量的逻辑,检测到变量不存在时直接返回 null 即可:
def sharedData = new Binding() // 直接重写实例的getVariable方法,找不到变量返回null sharedData.metaClass.getVariable = { String name -> if (variables.containsKey(name)) { return variables.get(name) } return null } def shell = new GroovyShell(sharedData) shell.evaluate("a=5; b=1") // 运行正常 // 不会抛出异常,a不存在时返回null shell.evaluate("a; b=1")
方案2:通过 CompilerConfiguration 配置全局缺失属性返回 null
通过 Groovy 编译器配置开启missingPropertyNull开关,所有访问不存在属性的场景会直接返回 null,无需修改 Binding 逻辑:
import org.codehaus.groovy.control.CompilerConfiguration def config = new CompilerConfiguration() // 开启缺失属性默认返回null的开关 config.missingPropertyNull = true def sharedData = new Binding() def shell = new GroovyShell(this.class.classLoader, sharedData, config) shell.evaluate("a=5; b=1") // 运行正常 // 不会抛出异常,a不存在时返回null shell.evaluate("a; b=1")
方案对比
- 方案1仅对当前绑定的 Binding 实例生效,适合需要区分不同脚本变量处理规则的场景
- 方案2对当前 GroovyShell 执行的所有脚本生效,适合全局统一处理的场景
内容的提问来源于stack exchange,提问作者ic10503
相关产品推荐
相关产品推荐

