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
Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.
if (var != null) { //... }
In groovy, the ==~ operator (aka the "match" operator) is used for regular expression matching. != is just a plain old regular "not equals".
You can use the getClass() method to determine the class of an object. Also, if you want to check if an object implements an Interface or Class, you can use the instanceof keyword. That's it about checking the datatype of an object in Groovy.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With