How can I determine if a variable exists from within the Groovy code running in the Scripting Engine?

你。 提交于 2020-12-04 16:00:39

问题


How can I determine if a variable exists from within the Groovy code running in the Scripting Engine?

The variable was put by ScriptEngine's put method


回答1:


In the groovy.lang.Script there is a method public Binding getBinding(). See also groovy.lang.Binding with method public boolean hasVariable(String name).

Thus you can simple check variable existence like

if (binding.hasVariable('superVariable')) {
// your code here
}



回答2:


// Example usage: defaultIfInexistent({myVar}, "default")
def defaultIfInexistent(varNameExpr, defaultValue) {
    try {
        varNameExpr()
    } catch (exc) {
        defaultValue
    }
}



回答3:


Variables injected by the Scripting Engine are held within binding.variables, so you can e.g. check for variable named xx:

if (binding.variables["xx"]) ...


来源:https://stackoverflow.com/questions/42465028/how-can-i-determine-if-a-variable-exists-from-within-the-groovy-code-running-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!