Scripted Methods and Objects
You can declare and use methods in BeanShell, just as you would inside a Java class:
intaddTwoNumbers(inta,intb){returna+b;}sum=addTwoNumbers(5,7);// 12
BeanShell methods may also have dynamic (loose) argument and return types.
add(a,b){returna+b;}foo=add(1,2);// 3foo=add("Hello ","Kitty");// "Hello Kitty"
In BeanShell, as in JavaScript and Perl, method closures can take the place of classes
for scripting objects (but in BeanShell you can also use the regular class
syntax). You can turn the context 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 that were set during the method call. To be useful, an object
may also need methods; so in BeanShell, methods may also contain methods
at any level. Here is a simple example:
user(n){name=n;reset(){("Reset user:"+name);}returnthis;// return user as object}bob=user("Bob");(bob.name);// "Bob"bob.reset();// prints "Reset user: Bob"
This example assigns the context of the user() method to the variable bob and refers to the field bob.name and the method bob.reset().
If you find this strange, don’t worry. The most common reason you’d want to script an object is to implement a Java interface, and you can do that using the standard Java anonymous inner class syntax, as we’ll discuss next, or just use a regular class. BeanShell gives you a lot ...