Reputation: 1810
I would like to create a command to use with the BeanShell library. I created a class like this:
package org.manu.bshformulas;
import bsh.CallStack;
import bsh.Interpreter;
public class IfNegative {
public static double invoke(Interpreter env, CallStack callstack,
double x, double y, double z) {
if(x < 0) {
return y;
}
return z;
}
}
And I want to use it in this main class:
package org.manu;
// imports....
public class TestFormulaParser {
private static final String COMMAND = "IfNotNegative(x, y, y / x)";
public static void main(String[] args) throws Exception {
double x=3;
double y=2;
Interpreter interprete = new Interpreter();
interprete.set("x", x);
interprete.set("y", y);
double output = Double.valueOf(interprete.eval(COMMAND).toString());
return output;
}
But it says to me that it does not recognize the IfNegative command.
How can I import the command?
Upvotes: 1
Views: 699
Reputation: 6802
@Manuelarte:
first of all, the name of compiled command created by you is IfNegative
and not IfNotNegative
Secondly, you need to import the package containing your compile commands like this.
importCommands("org.manu.bshformulas"); //import in bsh
you can put all of your compiled class in this single package, and with this import you can access them all.
Now you are invoking the beanshell script from your java code, for this to work correctly TestFormulaParser
should be as below :
public class TestFormulaParser {
private static final String COMMAND = "IfNegative(x, y, y / x)";
private static final String IMPORT = "importCommands(\"org.manu.bshformulas\");";
public static void main(String[] args) throws Exception {
double x = 3;
double y = 2;
Interpreter interprete = new Interpreter();
interprete.set("x", x);
interprete.set("y", y);
interprete.eval(IMPORT);
double output = Double.valueOf(interprete.eval(COMMAND).toString());
System.out.println("Output:" + output);
}
}
Upvotes: 3
Reputation: 425
I believe this answer might help you. In essence your script must import the commands. Assuming commands are a the directory commands/
addClassPath(".");
importCommands("commands");
Please be aware that if you have a command 'IfNegative' it must be in a file called 'IfNegative.bsh'.
Upvotes: 1