Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 318
ycomp Avatar asked Feb 26 '17 05:02

ycomp


People also ask

How do I display a variable in Groovy?

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.

How do you check if a variable exists or not in Java?

if (var != null) { //... }

What does != Mean in Groovy?

In groovy, the ==~ operator (aka the "match" operator) is used for regular expression matching. != is just a plain old regular "not equals".

How do I find the datatype of a variable in Groovy?

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.


2 Answers

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 } 
like image 105
Aliaksandr Pyrkh Avatar answered Sep 19 '22 13:09

Aliaksandr Pyrkh


// Example usage: defaultIfInexistent({myVar}, "default") def defaultIfInexistent(varNameExpr, defaultValue) {     try {         varNameExpr()     } catch (exc) {         defaultValue     } } 
like image 38
Maximilian Mordig Avatar answered Sep 18 '22 13:09

Maximilian Mordig