Groovy脚本含未定义属性时执行提取返回对象JSON出现异常如何解决
问题原因
你之前的方案失效是因为Expando的动态属性处理仅作用于MyClass实例本身,你传给GroovyShell的Binding上下文没有做缺失属性兼容,脚本执行时访问的是Binding中的属性,和MyClass继承Expando的能力完全无关。
解决方案
方案一:自定义容错Binding(通用方案,适配任意未知缺失属性)
重写Binding的getProperty方法,让所有不存在的属性默认返回null,避免抛出MissingPropertyException:
class TolerantBinding extends Binding { @Override Object getProperty(String property) { return hasVariable(property) ? getVariable(property) : null } }
修改业务代码,将默认Binding替换为自定义的TolerantBinding即可:
class MyClass { def myMethod() { def sharedData = new TolerantBinding() def shell = new GroovyShell(sharedData) String fileContent = new File("/path/to/test.groovy").text def result = shell.evaluate(fileContent) // 输出JSON结果 def json = new groovy.json.JsonBuilder(result).toPrettyString() println json return json } }
方案二:预先注入已知属性(适配已知缺失属性的场景)
如果明确知道脚本中会用到的缺失属性,也可以直接给默认Binding预先赋值,无需自定义类:
def sharedData = new Binding() // 预先注入缺失的a属性 sharedData.setVariable("a", null) def shell = new GroovyShell(sharedData)
注意事项
如果你的预期是拿到objComp对象,需要保证脚本中a != null才能走到对应的逻辑分支,可以根据业务需求调整TolerantBinding中缺失属性的默认返回值,或者直接修改脚本的判断逻辑。
内容的提问来源于stack exchange,提问作者ic10503
相关产品推荐
相关产品推荐

