Scripted Methods
BeanShell is a small, free, embeddable Java source interpreter with object scripting language features,
written in Java. BeanShell is a natural scripting language for Java.
This requires the library bsh-2.0b4.jar to be in classpath.
The following example shows writing scripted methods in beanshell script.
//Plain Java
int sumStrict ( int a, int b, int c ) {
return a + b + c;
}
//Loose Java
sumLoose ( a, b, c ) {
return a + b + c;
}
int x = sumStrict ( 2 , 4 , 6 ) ;
print ( x ) ;
y = sumLoose ( 2 , 4 , 6 ) ;
print ( y ) ;
z = sumLoose ( 1.2 , 2.4 , 3.6 ) ;
print ( z ) ;
a = sumLoose ( "BE " , "THE " , "CODER" ) ;
print ( a ) ;
b = sumLoose ( "Name : " , name, " " + date ) ;
print ( b ) ;
package com.bethecoder.tutorials.bean_shell;
import java.io.InputStreamReader;
import java.util.Date;
import bsh.EvalError;
import bsh.Interpreter;
public class ScriptedMethodsTest {
/**
* @param args
* @throws EvalError
*/
public static void main ( String [] args ) throws EvalError {
Interpreter interpreter = new Interpreter () ;
interpreter.set ( "name" , "Sriram" ) ;
interpreter.set ( "date" , new Date ()) ;
InputStreamReader reader = new InputStreamReader (
ScriptedMethodsTest. class .getClassLoader ()
.getResourceAsStream ( "scripted_meth.bsh" )) ;
interpreter.eval ( reader ) ;
}
}
It gives the following output,
12
12
7.199999999999999
BE THE CODER
Name : Sriram Sun Dec 04 01:01:10 IST 2011