3

I am executing groovy script in java:

final GroovyClassLoader classLoader = new GroovyClassLoader();
Class groovy = classLoader.parseClass(new File("script.groovy"));
GroovyObject groovyObj = (GroovyObject) groovy.newInstance();
groovyObj.invokeMethod("main", null);

this main method println some information which I want to save in some variable. How can I do it ?

hudi
  • 15,555
  • 47
  • 142
  • 246

1 Answers1

3

You would have to redirect System.out into something else..

Of course, if this is multi-threaded, you're going to hit issues

final GroovyClassLoader classLoader = new GroovyClassLoader();
Class groovy = classLoader.parseClass(new File("script.groovy"));
GroovyObject groovyObj = (GroovyObject) groovy.newInstance();

ByteArrayOutputStream buffer = new ByteArrayOutputStream() ;
PrintStream saveSystemOut = System.out ;
System.setOut( new PrintStream( buffer ) ) ;

groovyObj.invokeMethod("main", null);

System.setOut( saveSystemOut ) ; 
String output = buffer.toString().trim() ;

It's probably better (if you can) to write our scripts so they return something rather than dump to system.out

tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • thx a lot it works. I hae to use this method but I can rewrite groovy script – hudi Jun 22 '12 at 12:23
  • 1
    @hudi: You mention in [another question](http://stackoverflow.com/questions/11737904) that this code is running in a webapp. As Tim pointed out, **this will not work** in a multithreaded environment. And webapps are inherently multithreaded. It might seem to work if you're testing it on your own, but as soon as you have two people making requests at the same time the output will be horribly mangled. – Andrzej Doyle Jul 31 '12 at 10:33
  • this application should use just admin = one person but thx for warning – hudi Jul 31 '12 at 11:11