BeanShell Java - Scripting

1 What is BeanShell?

BeanShell is a small, free, embeddable, Java source interpreter with object scripting language features, written in Java. BeanShell executes standard Java statements and expressions directly without first compiling them. Also, with BeanShell the user can script object as simple method closure like those in Perl and JavaScript(tm). It is based on the Sun Java grammar and built with Sun’s JavaCC. In short, BeanShell is not just dynamically interpreted Java, but also a simple scripting language.BeanShell is a new kind of scripting language. BeanShell begins with the standard Java language and bridges it into the scripting domain in a natural way, but allowing the developer to relaxing types where appropriate. It is possible to write BeanShell scripts that look exactly like Java method code. But it's also possible to write scripts that look more like a traditional scripting language, while still maintaining the framework of the Java syntax.

2 BeanShell - Features

2.1 General

The interpreter is small, 175K jar file approximately.
  • Uses of the Java reflection API to provide runtime interpreted execution of Java statements and expressions.
  • Transparent access to all Java objects and APIs.
  • Runs in command line, console, applet and remote session server.
  • Works in applets as well as application.

2.2 Java Evaluation Features

  • Covers full Java statements & expression syntax and full Java arithmetic, logical and bitwise operations.
  • Emulation of strongly typed variables and methods.
  • Loops and control structures with breaks and returns.
  • Method invocations with polymorphic/overloaded method resolution.

2.3 Scripting Features

  • Scripted methods with strong or loose typing of arguments and return values.
  • Scripted objects with JavaScript-like method closures.
  • Scripted AWT/Swing event handlers.
  • Implementation of arbitrary Java interface
  • Convenience syntax for working with JavaBean properties, hashtables and primitive wrapper types.

2.4 Download and Run BeanShell

Download the latest JAR file from http://www.beanshell.org. if you just want to start playing around you may be able to launch the BeanShell desktop by simply double clicking on the BeanShell JAR file. More generally however you'll want to add the jar to your classpath so that you can work with your own classes and applications easily. To do this you can either drop the BeanShell JAR file into your Java extensions folder or add it to your classpath. (Important: If you put BeanShell in the extensions folder and wish to use it with BSF applications like Jakarta Ant you must install the bsf.jar in the same location).
To install as an extension place the bsh.jar file in your

$JAVA_HOME/jre/lib/ext folder.

Or add BeanShell to your classpath like this:

Linux: export CLASSPATH=$CLASSPATH:bsh-xx.jar

Windows:  set classpath = %classpath%;bsh-xx.jar
You can then run BeanShell in either a GUI or command line mode: </col> </col>
Command Runs
java bsh.Console Runs the graphical desktop
java bash.Interpreter Runs as text-only on the command line
java bsh.Interpreter filename [args] Runs a script file name 'filename'
It's also possible to call BeanShell from within your own Java applications, to reach it in a remote server mode for debugging, to use it as a servlet, or even in an applet. Example of BSH BeanShell understands standard Java statements, expressions, and method declarations. Statements and expressions are all of the normal things that you'd say inside a Java method such as variable declarations and assignments, method calls, loops, and conditionals. You can use these exactly as they would appear in Java, however in BeanShell you also have the option of working with "loosely typed" variables. That is, you can simply omit the types of variables that you use (both primitives and objects). BeanShell will only signal an error if you attempt to misuse the actual type of the variable. Here are some examples:
bsh % print(a);

3
bsh % foo="Foo"

bsh % print(foo);

Foo
bsh % print(1+2);

3
bsh % for(i=0;i < 10; i++)

print(i);

0

1

2

3

4

5

6

7

8

9

3 Examples

3.1 Creating a JFrame both in BSH and Java

Creating a window in BSH, done just in fly, as u compiled it. 

Script to create a JFrame in BSH

% frame(new JButton("Button"));

3.2 Script to create a JFrame in BSH

// 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);

3.3 Script to create a JFrame in Java

import javax.swing.JFrame;

public class FrameDemo{

        public FrameDemo(){

               JButton button = new JButton( "My Button" );

               this.setTitle("My Frame");

               this.getContentPane().add( button, "Center" );

               this.pack();

               this.setVisible(true);

        }

        public static void main( String[] args ){

               new FrameDemo();

        }

}

3.4 Auto Boxing and Unboxing

"Boxing" and "Unboxing" are the terms used to describe automatically wrapping a primitive type in a wrapper class and unwrapping it as necessary. Boxing is a feature of Java (SDK1.5) and has been supported in BeanShell for many years. BeanShell supports boxing and unboxing of primitive types. int i=5; Integer iw = new Integer(5); print( i * iw ); // 25 Vector v = new Vector(); v.put(1); int x = v.getFirstElement();

3.5 Bean Commands

</col> </col>
Commands Description
source(), run() Read a bsh script into this interpreter, or run it in a new interpreter
frame() Display a GUI component in a Frame or JFrame.
load(), save() Load or save serializable objects to a file.
cd(), cat(), dir(), pwd(), etc. Unix-like shell commands
exec() Run a native application
javap() Print the methods and fields of an object, similar to the output of the Java javap command.
setAccessibility() Turn on unrestricted access to private and protected components.
Tip: The BeanShell which() command will use the classpath mapping capability to tell you where exactly in your classpath a specified class is located: bsh % which( java.lang.String ); Jar: file:/usr/java/j2sdk1.4.0/jre/lib/rt.jar

3.6 Scripted Methods

You can declare and use methods in BeanShell just as you would in a Java class. int addTwoNumbers( int a, int b ) { return a + b; } sum = addTwoNumbers( 5, 7 ); // 12 Bsh methods may also allow dynamic (loose) argument and return types. add( a, b ) { return a + b; } foo = add(1, 2); // 3 foo = add("Bean", " Shell"); // "Bean Shell"

3.7 Calling BSH From Your Application

You can evaluate text and run scripts from within your application by creating an instance of the BeanShell interpreter and using the eval() or source() commands. You may pass in variable references to objects you wish to use in scripts via the set() method and retrieve results with the get() method.
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. Hope this small tutorial helps the beginners to get start with Bean Shell for Java – Scripting.