Skip to Content
Learning Java, 4th Edition
book

Learning Java, 4th Edition

by Patrick Niemeyer, Daniel Leuck
June 2013
Beginner
1007 pages
33h 32m
English
O'Reilly Media, Inc.
Content preview from Learning Java, 4th Edition

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 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() {
            print( "Reset user:"+name );
        }
        return this;  // return user as object
    }
    bob = user("Bob" );

    print( 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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan

Publisher Resources

ISBN: 9781449372477Errata PageSupplemental Content