How can I convince GroovyShell to maintain state over eval () calls?

I am trying to use Groovy to create an interactive scripting / macro mode for my application. The OSGi application, and most of the information that scripts may need, does not know in advance. I suggested that I could use GroovyShell and call eval () several times, constantly adding to the namespace when OSGi packages load. GroovyShell maintains statefulness across multiple eval calls, but does not define class definitions or methods.

purpose

: create a base class at startup time. When OSGi binds the load, create derived classes as needed.

+3
source share
3 answers

script. , , script, .

+1

, , evals, , , :

class C {{println 'hi'}}
new C()

...

new C()

, GroovyShell . , ( ), .

Class klass = this.getClass()
this.getMetaClass().getMethods().each {
  if (it.declaringClass.cachedClass == klass) {
    binding[it.name] = this.&"$it.name"
  }
}

, script (, , )...

String scriptText = ...
Script script = shell.parse(scriptText)
def returnValue = script.run()
Class klass = script.getClass()
script.getMetaClass().getMethods().each {
  if (it.declaringClass.cachedClass == klass) {
    shell.context[it.name] = this.&"$it.name"
  }
}
// do whatever with returnValue...

, , . , . , script 'klass' script invocations . , , , .

+2

, ?

Groovy

def binding = new Binding(x: 6, y: 4)
def shell = new GroovyShell(binding)
def expression = '''f = x * y'''
shell.evaluate(expression)
assert binding.getVariable("f") == 24

?

0

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


All Articles