Reputation: 43
I am working with beanshell bsh-2.0b4.jar file. I have build path and used it in a java program. I have managed to get the get the print statements from the console. But if a value is being returned, how to get the return value.
import java.io.*;
import bsh.Interpreter;
import bsh.EvalError;
public class CaptureDis {
/**
* @param args
*/
public static void main(String[] args) {
Interpreter i = new Interpreter();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps2 = System.out;
try {
//i.eval(System.out.println("System.out.println(\"test\");"));
i.eval("int x=2; int y=3; int res=x+y; return res");
i.getOut();
} catch (EvalError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String out = baos.toString();
System.setOut(ps2);
System.out.println(out);
}
}
Upvotes: 2
Views: 3082
Reputation: 425
I didn't test your script, but I suspect you are missing the import statement for HashSet. You actually don't need the HashSet declaration in the script. Since you set 'hs' before invocation it's known to the Interpreter. Your script should look like this:
srcCode = "for(i=0;i<10;i+=2){ hs.add(i); }";
Note that in reference to your first question, had you not set 'hs' before invocation you would need to explicitly return it, as the last evaluated expression ( hs.add(i) ) returns a Boolean. However, since you are passing in a reference to 'hs', it does not need to be returned at all.
Upvotes: 1
Reputation: 425
The eval method returns 'res'. You can actually omit the return statement in your script too as beanshell returns the last evaluated expression by default
Integer answer = (Integer) i.eval("int x=2; int y=3; int res=x+y; return res");
Upvotes: 0