Section B.2. Java Statements and Expressions


B.2. Java Statements and Expressions

At the prompt or in a BeanShell script, you can type standard Java statements and expressions. Statements and expressions are all of the normal things that you'd include in a Java method: variable declarations and assignments, method calls, loops, and conditionals. You can declare classes in the usual way if you want to, but BeanShell allows you to write statements outside of a class or method in an unstructured way as well.

You can type statements exactly as they would appear in Java. You also have the option of working in a more scripting-language-like fashion, with "loosely typed" variables and arguments. That is, you can simply be lazy and not declare the types of variables that you use (both primitives and objects). BeanShell will still give you an error if you attempt to misuse the actual contents of the variable. If you do declare types of variables or primitives, BeanShell will enforce them.

Here are some examples:

     foo = "Foo";     four = (2 + 2)*2/2;     print( foo + " = " + four );   // print(  ) is a bsh command     // do a loop     for (i=0; i<5; i++)         print(i);     // pop up an AWT frame with a button in it     button = new JButton("My Button");     frame = new JFrame("My Frame");     frame.getContentPane(  ).add( button, "Center" );     frame.pack(  );     frame.setVisible( true );

If you don't like the idea of "loosening" Java syntax at all, you can turn off this feature of BeanShell with the following command:

     setStrictJava( true );

B.2.1. Imports

By default, BeanShell imports all of the core Java packages for you. You can import your own classes using the standard Java import declaration:

     import mypackage.*;

In addition to regular package, class, and static imports, BeanShell can also import the methods and variables of an object instance into the current context using the importObject( ) command. For example:

     Map map = new HashMap(  );     importObject( map );     put("foo", "bar");     print( get("foo") ); // "bar"



    Learning Java
    Learning Java
    ISBN: 0596008732
    EAN: 2147483647
    Year: 2005
    Pages: 262

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net