How can I determine if a variable exists from within the Groovy code running in the Scripting Engine?
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
}
// Example usage: defaultIfInexistent({myVar}, "default")
def defaultIfInexistent(varNameExpr, defaultValue) {
try {
varNameExpr()
} catch (exc) {
defaultValue
}
}
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"]) ...