Thursday, June 14, 2007

Beanshell Tutorial (part 1)

Beanshell is a small, free, and embeddeble scripting engine. Beanshell executes standards Java statements and extends Java into the scripting domain.

Download the latest Beanshell JAR file (bsh-2.0b4.jar when this article is written) from http://www.beanshell.org. Put file bsh-2.0b4.jar in your classpath folder. To run Beanshell, you type:

java bsh.Console // run the graphical desktop

java bsh.Interpreter // run as text-only

java bsh.Interpreter filename [args] // the a script file

Basically, Beanshell syntax is very close to Java with some simplification. For example, you don't need to declare a variable, you can just use it. You can type

name = "Gusniawan";
print( name );

In this case, variable name becomes an untype variable.

You also can create a Java object directly from Beanshell.

// Use a hashtable
Hashtable hashtable = new Hashtable();
Date date = new Date();
hashtable.put( "today", date );


Beanshell will import Hashtable automatically from java.util.

You can catch an exception as well like you do in Java.
try
{

int i = 1/0;

}

catch ( ArithmeticException e )
{

print( e );

}
Or even simpler:
try
{

int i = 1/0;

}

catch ( e )
{

print( e );

}

No comments: