Beanshell is a small, free, and embedded Java source code interpreter. It has the characteristics of object-oriented scripting language and is implemented in Java. Beanshell can dynamically Execute standard Java statements and comes with simple script commands and syntax.
One important purpose of beanshell is to create a beanshell interpreter and run the eval () or source () command in your application to evaluate the value of the text expression and run the script. Just like the eval () function in MATLAB.
For example:
Interpeter bsh = new interpreter ();
// Evaluate statements and expressions
Bsh. eval ("foo = math. Sin (0.5 )");
Bsh. eval ("bar = Foo * 5; bar = math. Cos (bar );");
Bsh. eval ("for (I = 0; I <10; I ++) {print (/" Hello /");}");
// Same as abve using Java syntax and APIs only
Bsh. eval ("For (INT I = 0; I <10; I ++) {system. Out. println (/" Hello /");}");
// Source from files or streams
Bsh. Source ("myscript. bsh"); // or bsh. eval ("Source (/" myscript. bsh /")");
// Use set () and get () to pass objects in and out of Variables
Bsh. Set ("date", new date ());
Date = (date) bsh. Get ("date ");
// This wowould also work:
Date = (date) bsh. eval ("date ");
Bsh. eval ("year = date. getyear ()");
Integer year = (integer) bsh. Get ("year"); // primitives use wrappers
However, in an application a few days ago, I implemented some methods in a class in advance. I need to read a file to determine which method to call. The name of the method is stored in the file. So I used a statement similar to the following:
Import bsh. interpreter;
Public class main {
Public String STR = "Hello interpreter ";
Public static void main (string [] ARGs)
{
Main mainobj = new main ();
Mainobj. doprocess ();
}
Public void doprocess ()
{
Interpreter bshinterpreter = new interpreter ();
Try {
Bshinterpreter. eval ("printtext ()");
} Catch (bsh. evalerror ee ){
System. Out. println (EE. tostring ());
}
}
Private void printtext ()
{
System. Out. println (STR );
}
}
However, the error message is that the printtext () method cannot be found;
Sourced file: inline evaluation of: "printtext ();'': Command not found: printtext ()
The improvement method is as follows:
1. Change private void printtext () to public
2. Change bshinterpreter. eval ("printtext ()")
Bshinterpreter. Set ("thisobject", this); // assign this object to the variable thisobject
Bshinterpreter. eval ("thisobject." + "printtext ()"); // This. printtext ()
21-04-2010, Stavanger