gpt4 book ai didi

java - 使用beanshell运行java代码

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:08 27 4
gpt4 key购买 nike

好吧,我有一些简单的代码,我想使用 beanshell 解释器运行,我正在尝试弄清楚如何做类似的事情:

String s = "int x = 5; System.out.println(x);" 
Interpreter i = new Interpreter();
i.eval(s); //THIS

现在真正的问题出现了,如何将“i.eval(s)”的输出转换回字符串,以便我可以在其他地方使用输出?

如果已经有人问过这个问题或者某处是否有简单的文档,我深表歉意。我找不到任何有帮助的东西。

非常感谢。

最佳答案

使用以下解决方案解决。

    Interpreter i = new Interpreter(); // Create a new BeanShell interpreter.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream stdout = System.out; // Save System.out
System.setOut(ps); // Set the out to the PrintStream
try{
i.eval(s);
}catch (Exception e){
return "Error";
}
String out = baos.toString(); // Get the output
System.setOut(stdout); // Reset the output

关于java - 使用beanshell运行java代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21950729/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com