Home |
Back |
Contents |
Next |
To install as an extension place the bsh.jar file in your $JAVA_HOME/jre/lib/ext folder. (OSX users: place the bsh.jar in /Library/Java/Extensions or ~/Library/Java/Extensions for individual users.) Or add BeanShell to your classpath like this: unix: export CLASSPATH=$CLASSPATH:bsh-xx.jar windows: set classpath %classpath%;bsh-xx.jar |
Tip: You can modify the classpath from within BeanShell using the addClassPath() and setClassPath() commands. |
java bsh.Console // run the graphical desktop or java bsh.Interpreter // run as text-only on the command line or java bsh.Interpreter filename [ args ] // run script file |
foo = "Foo"; four = (2 + 2)*2/2; print( foo + " = " + four ); // print() is a BeanShell command // Do a loop for (i=0; i<5; i++) print(i); // Pop up a frame with a button in it button = new JButton( "My Button" ); frame = new JFrame( "My Frame" ); frame.getContentPane().add( button, "Center" ); frame.pack(); frame.setVisible(true); |
Tip: BeanShell commands are not really "built-in" but are simply BeanShell scripts that are automatically loaded from the classpath. You can add your own scripts to the classpath to extend the basic command set. |
int addTwoNumbers( int a, int b ) { return a + b; } sum = addTwoNumbers( 5, 7 ); // 12 |
add( a, b ) { return a + b; } foo = add(1, 2); // 3 foo = add("Oh", " baby"); // "Oh baby" |
ActionListener scriptedListener = new ActionListener() { actionPerformed( event ) { ... } } |
ml = new MouseListener() { mousePressed( event ) { ... } // handle the rest invoke( name, args ) { print("Method: "+name+" invoked!"); } |
foo() { print("foo"); x=5; bar() { print("bar"); } return this; } myfoo = foo(); // prints "foo" print( myfoo.x ); // prints "5" myfoo.bar(); // prints "bar" |
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"); |
Tip: In the above example the Interpreter's eval() method also returned the value of bar as the result of the evaluation. |
Home |
Back |
Contents |
Next |