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 ?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

thx a lot it works. I hae to use this method but I can rewrite groovy script
@hudi: You mention in another question 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.
this application should use just admin = one person but thx for warning

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.