문제

I create a groovy engine with the GroovyShell class. Then I run a bunch of statements with the "evaluate" method.
Is there a way to catch the output of the engine so I can get "println" calls output?
Currently it goes to stdout although it is a swing application.

도움이 되었습니까?

해결책

You can just assign your custom Writer (eg. StringWriter) to out property in the binding and pass it to the GroovyShell.

def binding = new Binding();
binding.setProperty("out", new YourWriter())
new GroovyShell(binding);

다른 팁

You can set a scriptBaseClass with a println method and you are free to operate on top of the value. Remember the user still can do System.out.println, but you can blacklist it, if needed.

import org.codehaus.groovy.control.CompilerConfiguration

def script = """
  a = 10
  println a
  println "echo"
"""

abstract class Printer extends Script {
  void println(obj) {
    this.binding.printed << obj
  }
}

def config = new CompilerConfiguration(scriptBaseClass: Printer.class.name)
def binding = new Binding([printed: []])

new GroovyShell(this.class.classLoader, binding, config).evaluate script

assert binding.variables.printed.contains( 10 )
assert binding.variables.printed.contains( "echo" )
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top