Home |
Back |
Contents |
Next |
import bsh.Interpreter; Interpreter i = new Interpreter(); // Construct an interpreter i.set("foo", 5); // Set variables i.set("date", new Date() ); Date date = (Date)i.get("date"); // retrieve a variable // Eval a statement and get the result i.eval("bar = foo*10"); System.out.println( i.get("bar") ); // Source an external script file i.source("somefile.bsh"); |
Note: It is not necessary to add a trailing ";" semi-colon at the end of the evaluated string. BeanShell always adds one at the end of the string. |
Object result = i.eval( "long time = 42; new Date( time )" ); // Date Object result = i.eval("2*2"); // Integer |
reader = new FileReader("myscript.bsh"); i.eval( reader ); |
try { i.eval( script ); } catch ( EvalError e ) { // Error evaluating script } |
String getErrorText() { |
int getErrorLineNumber() { |
String getErrorSourceFile() { |
try { i.eval( script ); } catch ( TargetError e ) { // The script threw an exception Throwable t = e.getTarget(); print( "Script threw exception: " + t ); } catch ( ParseException e ) { // Parsing error } catch ( EvalError e ) { // General Error evaluating script } |
i.source("myfile.bsh"); |
import bsh.Interpreter; i=new Interpreter(); i.eval("myobject=object()" ); i.set("myobject.bar", 5); i.eval("ar=new int[5]"); i.set("ar[0]", 5); i.get("ar[0]"); |
// script the method globally i.eval( "actionPerformed( e ) { print( e ); }"); // Get a reference to the script object (implementing the interface) ActionListener scriptedHandler = (ActionListener)i.eval("return (ActionListener)this"); // Use the scripted event handler normally... new JButton.addActionListener( scriptedHandler ); |
Interpreter interpreter = new Interpreter(); // define a method called run() interpreter.eval("run() { ... }"); // Fetch a reference to the interpreter as a Runnable Runnable runnable = (Runnable)interpreter.getInterface( Runnable.class );The interface generated is an adapter (as are all interpreted interfaces). It does not interfere with other uses of the global scope or other references to it. We should note also that the interpreter does *not* require that any or all of the methods of the interface be defined at the time the interface is generated. However if you attempt to invoke one that is not defined you will get a runtime exception.
Tip: You can clear all variables, methods, and imports from a scope using the clear() command. |
Note: There is serious Java bug that affects BeanShell serializability in Java versions prior to 1.3. When using these versions of Java the primitive type class identifiers cannot be de-serialized. See the FAQ for a workaround. |
// From BeanShell object.namespace.prune(); // From Java object.getNameSpace().prune(); |
// From BeanShell bind( object, this.namespace ); // From Java bsh.This.bind( object, namespace, interpreter ); |
Home |
Back |
Contents |
Next |