How to determine if a variable exists from Groovy code running in the Scripting Engine?

How to determine if a variable exists from Groovy code running in the Scripting Engine?

The variable was placed ScriptEngine put method

+13
source share
3 answers

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

This way you can just check for the existence of a variable, e.g.

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

The variables introduced by the Scripting Engine are stored within binding.variables , so you can, for example, check a variable called xx :

 if (binding.variables["xx"]) ... 
+3
source
 // Example usage: defaultIfInexistent({myVar}, "default") def defaultIfInexistent(varNameExpr, defaultValue) { try { varNameExpr() } catch (exc) { defaultValue } } 
0
source

Source: https://habr.com/ru/post/1264734/


All Articles