Scripted Methods and Objects

You can declare and use methods in BeanShell, just as you would inside a Java class:

int addTwoNumbers( int a, int b ) {
    return a + b;
}

sum = addTwoNumbers( 5, 7 );  // 12

BeanShell methods may also have dynamic (loose) argument and return types.
add( a, b ) {
    return a + b;
}

foo = add(1, 2);                // 3
foo = add("Hello ", "Kitty");   // "Hello Kitty"

In BeanShell, as in JavaScript and Perl, method closures take the place of scripted objects. You can turn the results of a method call into an object reference by having the method return the special value this. You can then use the this reference to refer to any variables which were set during the method call. An object is useful only if it has methods; so in BeanShell, methods may also contain methods at any level. Here is a simple example:

foo( ) {
    print("foo");
    x=5;

    bar( ) {
        print("bar");
    }

    return this;
}

myfoo = foo( );    // "foo"
print( myfoo.x ); // "5"
myfoo.bar( );      // "bar"

Get Learning Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.