簡體   English   中英

使用beanshell運行java代碼

[英]Using beanshell to run java code

好的,所以我有一些我想使用 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

根據文檔, eval 方法返回一個包含評估結果的對象。 嘗試將其轉換為字符串。

主.java

package org.example; // Your package 

import bsh.EvalError;
import bsh.Interpreter;

public class Main {

    public static void main(String[] args) throws EvalError {
        String s = "int x = 5; System.out.println(x);";
        Interpreter i = new Interpreter();
        i.eval(s);
    }
}

構建.gradle

implementation 'org.beanshell:bsh:2.0b5'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM