String scriptText = "int a = 12;"; ImportCustomizer ic = new ImportCustomizer(); ic.addImports("my.package.MyClass"); CompilerConfiguration cc = new CompilerConfiguration(); cc.addCompilationCustomizers(ic); Binding gb = new Binding(); gb.setVariable("myObject", myObject); GroovyShell gsh = new GroovyShell(gb, cc); gsh.evaluate(scriptText); Object res = gsh.evaluate(scriptText); 

The development environment says line

 gb.setVariable("myObject", myObject); 

is a mistake. How to fix?

  • one
    And what error does he tell you, do not tell us from the principle? - Alexey Shimansky
  • It underlines this line in red and when compiled, says Error: (86, 36) error: cannot find symbol variable myObject - dhred
  • Well. In Google Translate, if you drive in, what will it give out? ....... you have a variable named myObject where? - Alexey Shimansky
  • The documentation says that it is not required in the declaration: With such a binding, there should be no declaration of the myObject variable in the script: neither def myObject, nor MyClass myObject. It has already been declared, just use it immediately: myObject.method (); myObject.prop = ... - dhred
  • What documentation? Show link. - Roman

1 answer 1

myObect should not be declared in a script that you want to run, in which you want to use this myObect , but in the program itself, it should be!

Java

  MyClass myObject = new MyClass(); ... gb.setVariable("myObject", myObject); ... 

Groovy Script

  ... myObject.method() myObject.prop = 123 // Все эти действия над объектом, println(myObject.prop) // переданном скрипту через binding ... 

You can use some variables in the script and if one of them is def myObject, then it will block the object will not be visible to the script, but its own variable will be visible.

Groovy Script

  ... def myObject // это скроет от скрипта binding "myObject" ... myObject.method() myObject.prop = 123 // Все эти действия уже над переменной myObject, println(myObject.prop) // определённой в скрипте, а не переданной ему в binding ...