如何在java中获得groovy脚本的输出 [英] How to get output of groovy script in java

查看:823
本文介绍了如何在java中获得groovy脚本的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这个主要方法println我想要保存在一些变量中的一些信息。如何才能做到这一点?

解决方案

您必须将System.out重定向到其他位置。



当然,如果这是多线程的,你会遇到问题

 最终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();

编写我们的脚本可能会更好(如果可以的话),以便它们返回一些内容而不是转储到系统.out


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 ?

解决方案

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

这篇关于如何在java中获得groovy脚本的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆