`
jetway
  • 浏览: 483795 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

beanshell

    博客分类:
  • java
阅读更多

Table of Contents

<!-- Auto generated table of contents -->


<!--PAGE BREAK--><!-- Auto generated table of contents -->

Introduction

This document is about BeanShell. BeanShell is a small, free, embeddable Java source interpreter with object scripting language features, written in Java. BeanShell executes standard Java statements and expressions but also extends Java into the scripting domain with common scripting language conventions and syntax. BeanShell is a natural scripting language for Java.

 

Scripting vs. Application Languages

Traditionally, the primary difference between a scripting language and a compiled language has been in its type system: the way in which you define and use data elements. You might be thinking that there is a more obvious difference here - that of "interpreted" code vs. compiled code. But the compiler in and of itself does not fundamentally change the way you work with a language. Nor does interpreting a language necessarily make it more useful for what we think of as "scripting". It is the type system of a language that makes it possible for a compiler to analyze the structure of an application for correctness. Without types, compilation is reduced to just a grammar check and an optimization for speed. From the developer's perspective, it is also the type system that characterizes the way in which we interact with the code.

Types are good. Without strongly type languages it would be very hard to write large scale systems and make any assertions about their correctness before they are run. But working with types imposes a burden on the developer. Types are labels and labeling things can be tedious. It can be especially tedious during certain kinds of development or special applications where it is flexibility and not program structure that is paramount. There are times where simplicity and ease of use is a more important criterion.

This is not just rationalization to cover some underlying laziness. Productivity affects what people do and more importantly do *not* do in the real world, much more than you might think. There is a lot of important software that exists in the world today only because the cost/benefit ratio in some developer's mind reached a certain threshold.

Unit testing - one of the foundations of writing good code - is a prime example. Unit tests for well written code are, in general, vitally important as a collective but almost insignificant individually. It's a "tragedy of the commons" that leads individual developers to repeatedly weigh the importance of writing another unit test with working on "real code". Give developers have a tool that makes it easy to perform a test with a line or two of code they will probably use it. If, moreover, it is also a tool that they enjoy using during their development process - that saves the time, they will be even more inclined to use it.

Customizability through scripting also opens the door to applications that are more powerful than the sum of their parts. When users can extend, enhance, and add to their applications they use them in new and unexpected ways.

Scripting is powerful.

 

Tearing Down the Barriers

Traditionally scripting languages have traded in the power of types for simplicity. Most scripting languages distill the type system to just one or a handful of types such as strings, numbers, or simple lists. This is sufficient for many kinds of scripting.

Many scripting languages operate in a loose, unstructured land - a place dominated by text and course-grained tools. As such these scripting languages have evolved sophisticated mechanisms for working with these simple types (regular expressions, pipes, etc.). As a result there has developed a casm between the scripting languages and the application languages created by the collapse of the type system in-between. The scripting languages have remained a separate species, isolated and speaking a different dialect from their brothers the application languages.

BeanShell is a new kind of scripting language. BeanShell begins with the standard Java language and bridges it into the scripting domain in a natural way, but allowing the developer to relaxing types where appropriate. It is possible to write BeanShell scripts that look exactly like Java method code. But it's also possible to write scripts that look more like a traditional scripting language, while still maintaining the framework of the Java syntax.

BeanShell emulates typed variables and parameters when they are used. This allows you to "seed" your code with strong types where appropriate. You can "shore up" repeatedly used methods as you work on them, migrating them closer to Java. Eventually you may find that you want to compile these methods and maintain them in standard Java. With BeanShell this is easy. BeanShell does not impose a syntactic boundary between your scripts and Java.

But the bridge to Java extends much deeper than simple code similarity. BeanShell is one of a new breed of scripting languages made possible by Java's advanced reflection capabilities. Since BeanShell can run in the same Java virtual machine as your application, you can freely work with real, live, Java objects - passing them into and out of your scripts. Combined with BeanShell's ability to implement Java interfaces, you can achieve seamless and simple integration of scripting into your Java applications. BeanShell does not impose a type boundary between your scripts and Java.

 

History

What seems like an eternity ago, back in the summer of 1993, I was working at Southwestern Bell Technology Resources and I was infatuated with the Tcl/Tk scripting language. On the advice of someone at Sun I also began playing around a bit with the Oak language written by James Gosling. Little did I know that within just a few years Oak, which would become Java, would not only spark a revolution, but that I would be writing one of the first books on the new Java language (Exploring Java, O'Reilly & Associates) and creating Java's first scripting language, BeanShell, drawing inspiration from Tcl.

BeanShell's first public release was not until 1997, but I had been poking at it in one form or another for some time before that. BeanShell as a language became practical when Sun added reflection to the Java language in version 1.1. After that, and after having seen its value in helping me create examples and snippets for the second edition of my book, I decided to try to polish it up and release it.

BeanShell has slowly, but steadily gained popularity since then. It has grown in fits and spurts as its contributor's time has allowed. But recently BeanShell has achieved a sort of critical mass. BeanShell is distributed with Emacs as part of the JDE and with Sun Microsystem's NetBeans / Forte for Java IDEs. BeanShell is also bundled by BEA with their Weblogic application server. We've had reports of BeanShell being used everywhere from the high energy physics laboratory CERN, to classrooms teaching programming to nine year olds. BeanShell is being used in everything from large financial applications all the way down to embedded systems floating in Buoys in the pacific ocean. I attribute this success to the power of the open source development model and owe many thanks to everyone who has contributed.

 

Conclusion

I believe that BeanShell is the simplest and most natural scripting language for Java because it is, foremost, Java. BeanShell draws on a rich history of scripting languages for its scripting syntax and uses it to very conservatively extend the Java language into this new domain. I hope that you have half as much fun using BeanShell as I have had working on it and I welcome all comments and suggestions.

 


<!--PAGE BREAK-->

Quick Start

Welcome to BeanShell. This is a crash course to get you going. We'll leave out many important options and details. Please see the rest of the user's guide for more information.

 

Download and Run BeanShell

Download the latest JAR file from http://www.beanshell.org and start up BeanShell either in the graphical desktop mode or on the command line.

If you just want to start playing around you may be able to launch the BeanShell desktop by simply double clicking on the BeanShell JAR file. More generally however you'll want to add the jar to your classpath so that you can work with your own classes and applications easily.

To do this you can either drop the BeanShell JAR file into your Java extensions folder or add it to your classpath. (Important: If you put BeanShell in the extensions folder and wish to use it with BSF applications like Jakarta Ant you must install the bsf.jar in the same location).

 

To install as an extension place the bsh.jar file in your 
$JAVA_HOME/jre/lib/ext folder.  (OSX users: place the bsh.jar in 
/Library/Java/Extensions or ~/Library/Java/Extensions for individual users.)

Or add BeanShell to your classpath like this:

unix:     export CLASSPATH=$CLASSPATH:bsh-xx.jar
windows:  set classpath %classpath%;bsh-xx.jar

 

 

Tip:
You can modify the classpath from within BeanShell using the addClassPath() and setClassPath() commands.

You can then run BeanShell in either a GUI or command line mode:

 

    java bsh.Console       // run the graphical desktop
or
    java bsh.Interpreter   // run as text-only on the command line
or
    java bsh.Interpreter filename [ args ] // run script file

 

It's also possible to call BeanShell from within your own Java applications, to reach it in a remote server mode for debugging, to use it as a servlet, or even in an applet. See "BeanShell Modes of Operation" for more details.

The BeanShell GUI

The BeanShell GUI desktop is meant to allow some experimentation with the features of BeanShell. It is not intended to be a replacement for a full featured IDE. Please check out the jEdit editor for an example of a full featured development environment based in part on BeanShell scripting capabilities.

Upon starting the BeanShell in GUI mode a console window will open. By right clicking on the desktop background you can open additional console windows and other tools such as a simple class browser.

Each console window runs a separate instance of the BeanShell interpreter. The graphical console supports basic command history, line editing, cut and paste, and even class and variable name completion. From the console you can open a simple editor window. In it you can write scripts and use the 'eval' option to evaluate the text in the attached console's workspace or a new workspace.

 

Java Statements and Expressions

BeanShell understands standard Java statements, expressions, and method declarations. Statements and expressions are all of the normal things that you'd say inside a Java method such as variable declarations and assignments, method calls, loops, and conditionals.

You can use these exactly as they would appear in Java, however in BeanShell you also have the option of working with "loosely typed" variables. That is, you can simply omit the types of variables that you use (both primitives and objects). BeanShell will only signal an error if you attempt to misuse the actual type of the variable.

Here are some examples:

 

foo = "Foo";    
four = (2 + 2)*2/2;
print( foo + " = " + four );  // print() is a BeanShell command

// Do a loop
for (i=0; i<5; i++)
    print(i);   

// Pop up a 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);

 

 

Useful BeanShell Commands

In the previous example we used a convenient "built-in" BeanShell command called print(), to display values. print() does pretty much the same thing as System.out.println() except that it insures that the output always goes to the command line. print() also displays some types of objects (such as arrays) more verbosely than Java would. Another related command is show(), which toggles on and off automatic display of the result of every line you type.

Here are a few other examples of BeanShell commands:

  • source(), run() - Read a bsh script into this interpreter, or run it in a new interpreter
  • frame() - Display a GUI component in a Frame or JFrame.
  • load(), save() - Load or save serializable objects to a file.
  • cd(), cat(), dir(), pwd(), etc. - Unix-like shell commands
  • exec() - Run a native application
  • javap() - Print the methods and fields of an object, similar to the output of the Java javap command.
  • setAccessibility() - Turn on unrestricted access to private and protected components.

See the complete list of BeanShell Commands for more information.

 

 

Tip:
BeanShell commands are not really "built-in" but are simply BeanShell scripts that are automatically loaded from the classpath. You can add your own scripts to the classpath to extend the basic command set.

 

Scripted Methods

You can declare and use methods in BeanShell just as you would in a Java class.

 

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

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

Bsh methods may also allow dynamic (loose) argument and return types.

 

add( a, b ) {
    return a + b;
}

foo = add(1, 2);            // 3
foo = add("Oh", " baby");   // "Oh baby"

 

Implementing Interfaces

Note: implementing arbitrary interfaces requires BeanShell be run under a Java 1.3 or higher environment.

You can use the standard Java anonymous inner class syntax to implement an interface type with a script. For example:

 

ActionListener scriptedListener = new ActionListener() {
    actionPerformed( event ) { ... }
}

You don't have to script all of the methods of an interface. You can opt to script only those that you intend to call if you want to. The calling code will simply throw an exception if it tries to invoke a method that isn't defined. If you wish to override the behavior of a large number of methods - say to produce a "dummy" adapter for logging - you can implement a special method signature: invoke(name, args) in your scripted object. The invoke() method is called to handle any undefined method invocations:

 

ml = new MouseListener() {
    mousePressed( event ) { ... }
    // handle the rest
    invoke( name, args ) { print("Method: "+name+" invoked!");
}

 

Scripted Objects

In BeanShell, as in JavaScript and Perl, method "closures" allow you to create 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 reference to refer to any variables set during the method call. Useful objects need methods of course, so in BeanShell scripted methods may also contain methods at any level. For example:

 

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

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

    return this;
}

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

If this "closure" thing seems strange to don't worry. It's just an evolutionary step that languages acquired along the path to Objects. Please see the user's manual for a more thorough explanation.

Within your scripts, BeanShell scripted objects (i.e. any 'this' type reference like myFoo in the previous example) can automatically implement any Java interface type. When Java code calls methods on the interface the corresponding scripted methods will be invoked to handle them. BeanShell will automatically "cast" your scripted object when you attempt to pass it as an argument to a method that takes an interface type. For passing script references outside of BeanShell, you can perform an explicit cast where necessary. Please see the user manual for full details.

 

Calling BeanShell From Your Application

You can evaluate text and run scripts from within your application by creating an instance of the BeanShell interpreter and using the eval() or source() commands. You may pass in variable references to objects you wish to use in scripts via the set() method and retrieve results with the get() method.

 

import bsh.Interpreter;

Interpreter i = new Interpreter();  // Construct an interpreter
i.set("foo", 5);                    // Set variables
i.set("date", new Date() ); 

Date date = (Date)i.get("date");    // retrieve a variable

// Eval a statement and get the result
i.eval("bar = foo*10");             
System.out.println( i.get("bar") );

// Source an external script file
i.source("somefile.bsh");

 

 

Tip:
In the above example the Interpreter's eval() method also returned the value of bar as the result of the evaluation.

 

Conclusion

We hope this brief introduction gets you started. Please see the full user manual for more details. Please consult the mailing list archives for more useful information. http://www.beanshell.org/


<!--PAGE BREAK-->

Basic Syntax

BeanShell is, foremost, a Java interpreter. So you probably already know most of what you need to start scripting with BeanShell. This section describes specifically what portion of the Java language BeanShell interprets and how BeanShell extends it or "loosens" it to be more scripting-language-like.

 

Standard Java Syntax

In a BeanShell script (and on the command line) you can type normal Java statements and expressions and display the results. Statements and expressions are the kinds of things you normally find inside of a Java method: variable assignments, method calls, math expressions, for-loops, etc.

Here are some examples:

 

/*
    Standard Java syntax
*/

// Use a hashtable
Hashtable hashtable = new Hashtable();
Date date = new Date();
hashtable.put( "today", date );

// Print the current clock value
print( System.currentTimeMillis() );

// Loop
for (int i=0; i<5; i++)
    print(i);

// Pop up a frame with a button in it
JButton button = new JButton( "My Button" );
JFrame frame = new JFrame( "My Frame" );
frame.getContentPane().add( button, "Center" );
frame.pack();
frame.setVisible(true);

You can also define your own methods and use them just as you would inside a Java class. We'll get to that in a moment.

Loosely Typed Java Syntax

In the examples above, all of our variables have declared types. e.g. "JButton button". Beanshell will enforce these types, as you will see if you later try to assign something other than a JButton to the variable "button" (you will get an error message). However BeanShell also supports "loose" or dynamically typed variables. That is, you can refer to variables without declaring them first and without specifying any type. In this case BeanShell will do type checking where appropriate at runtime. So, for example, we could have left off the types in the above example and written all of the above as:

 

/*
    Loosely Typed Java syntax
*/

// Use a hashtable
hashtable = new Hashtable();
date = new Date();
hashtable.put( "today", date );

// Print the current clock value
print( System.currentTimeMillis() );

// Loop
for (i=0; i<5; i++)
    print(i);

// Pop up a 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);

This may not seem like it has saved us a great deal of work. But you will see the difference when you come to rely on scripting as part of your development and testing process; especially for in interactive use.

When a "loose" variable is used you are free to reassign it to another type of Java object later. Untyped BeanShell variables can also freely hold Java primitive values like int and boolean. Don't worry, BeanShell always knows the real types and only lets you use the values where appropriate. For primitive types this includes doing the correct numeric promotion that the real Java language would do when you use them in an expression.

 

Exception Handling

Exception handling using try/catch blocks works just as it does in Java. For example:

 

try {
    int i = 1/0;
} catch ( ArithmeticException e ) {
    print( e );
}

But you can loosely type your catch blocks if you wish:

 

try {
    ...
} catch ( e ) { 
    print( "caught exception: "+e );
}

 

Basic Scoping of Variables

 

Note:
As of BeanShell version 1.3 the default scoping of loosely typed variables was changed to be more consistent with Java. BeanShell still supports an alternate scoping used in earlier versions. This mode can be enabled for legacy code by setting the system property "localscoping" to true. See appendix "Local Scoping".

Variable scoping in BeanShell behaves, wherever possible, just like that in Java. Ordinary Java, however, does not offer "loose" variables (variables that can be used without being declared first). So we must define their behavior within BeanShell. We'll see in the next section that untyped variables - variables that are not declared and not assigned a value elsewhere - default to the local scope. This means that, in general, if you assign a value to a variable without first declaring it, you are creating a new local variable in the current scope.

 

Blocks

Blocks are statements between curly braces {}. In BeanShell, as in Java, blocks define a level of scope for typed variables: typed variables declared within a block are local to the block. Other assignments within the block occur, as always, wherever the variable was defined.

Untyped variables in BeanShell, however, are not constrained by blocks. Instead they act as if they were declared at the outer (enclosing) scope's level. With this in mind, BeanShell code looks just like Java code. In BeanShell if you declare a typed variable within a block it is local to the block. But if you use an untyped variable (which looks just like an ordinary assignment in Java) it behaves as an assignment to the enclosing scope.

This will make sense with a few examples:

 

 

// Arbitrary code block
{
    y = 2;      // Untyped variable assigned
    int x = 1;  // Typed variable assigned
}
print( y ); // 2
print( x ); // Error! x is undefined.

// Same with any block statement: if, while, try/catch, etc.
if ( true ) {
    y = 2;      // Untyped variable assigned
    int x = 1;  // Typed variable assigned
}
print( y ); // 2
print( x ); // Error! x is undefined.

Variables declared in the for-init area of a for-loop follow the same rules as part of the block:

 

for( int i=0; i<10; i++ ) {  // typed for-init variable
    j=42;
}
print( i ); // Error! 'i' is undefined.
print( j ); // 42

for( z=0; z<10; z++ ) { }   // untyped for-init variable
print( z ); // 10

 

Variable Modifiers

The standard Java variable modifiers may be used on typed variables: private / protected / public, final, transient, volatile, static. Only 'final' is currently implemented. The others are currently ignored.

Modifiers may not be applied to untyped variables.

Convenience Syntax

In BeanShell you may access JavaBean properties as if they were fields:

 

button = new java.awt.Button();
button.label = "my button";  // Equivalent to: b.setLabel("my button");
print( button.label );       // Equivalent to print( b.getLabel() );

JavaBean properties are simply pairs of "setter" and "getter" methods that adhere to a naming convention. In the above example BeanShell located a "setter" method with the name "setLabel()" and used it to assign the string value. It then found the method named getLabel() to retrieve the value.

Boolean properties may optionally use the syntax "is" for their "getter". e.g.

 

Float f = new Float(42f);
print( f.infinite );  // Equivalent to print( f.isInfinite() ); // false

If there is any ambiguity with an actual Java field name of the object (e.g. label in the above example) then the actual field name takes precedence. If you wish to avoid any ambiguity BeanShell provides an additional, uniform syntax for accessing both Java Bean properties and Hashtable or Map entries. You may use the "{}" curly brace construct with a String identifier as a qualifier on any variable of the appropriate type:

 

b = new java.awt.Button();
b{"label"} = "my button";  // Equivalent to: b.setLabel("my button");

h = new Hashtable();
h{"foo"} = "bar";          // Equivalent to: h.put("foo", "bar");

Where the java.util.Collections API is available, Maps are also supported.

 

Enhanced 'for' Loop

BeanShell supports the Java 1.5 style enhanced for-loop for iterating over collections and array types. (Note that you do not have to be running Java 1.5 to use this feature).

 

List foo = getSomeList();

for ( untypedElement : foo ) 
	print( untypedElement ); 

for ( Object typedElement: foo ) 
	print( typedElement );

int [] array = new int [] { 1, 2, 3 };

for( i : array ) 
	print(i);

for( char c : "a string" )
	print( c ); 

Supported iterable types include all the obvious things.

  • JDK 1.1+ - (no collections): Enumeration, arrays, Vector, String, StringBuffer
  • JDK 1.2+ - (w/collections): Collections, Iterator

See also the BshIterator API which supports the ehanced for-loop and allows iteration over these types using the dynamically loaded BeanShell Collection manager.

 

Switch Statements

In BeanShell, the switch statement may be used not only with numeric types but with objects. For example, you may switch on Dates and Strings which are compared for equality with their equals() methods:

 

dateobj = new Date();

switch( dateobj ) 
{
	case newYears:
		break;
	case christmas:
		break;
	default:
}

 

Auto Boxing and Unboxing

"Boxing" and "Unboxing" are the terms used to describe automatically wrapping a primitive type in a wrapper class and unwrapping it as necessary. Boxing is a feature of Java (SDK1.5) and has been supported in BeanShell for many years.

BeanShell supports boxing and unboxing of primitive types. For example:

 

int i=5;
Integer iw = new Integer(5);
print( i * iw );  // 25

Vector v = new Vector();
v.put(1); 
int x = v.getFirstElement();

 

Importing Classes and Packages

In BeanShell as in Java, you can either refer to classes by their fully qualified names, or you can import one or more classes from a Java package.

 

 

// Standard Java
import javax.xml.parsers.*;
import mypackage.MyClass;

 

In BeanShell import statements may appear anywhere, even inside a method, not just at the top of a file. In the event of a conflict, later imports take precedence over earlier ones.

A somewhat experimental feature is the "super import". With it you may automatically import the entire classpath, like so:

 

import *;

The first time you do this BeanShell will map out your entire classpath; so this is primarily intended for interactive use. Note that importing every class in your classpath can be time consuming. It can also result in a lot of ambiguities. Currently BeanShell will report an error when resolving an an ambiguous import from mapping the entire classpath. You may disambiguate it by importing the class you intend.

 

 

Tip:
The BeanShell which() command will use the classpath mapping capability to tell you where exactly in your classpath a specified class is located:
bsh % which( java.lang.String );
Jar: file:/usr/java/j2sdk1.4.0/jre/lib/rt.jar

See "Class Path Management" for information about modifying the BeanShell classpath at run-time with the addClassPath() or setClassPath() commands.

Also see "BeanShell Commands" for information about importing new BeanShell commands from the classpath.

 

Default Imports

By default, common Java core and extension packages are imported for you. They are, in the order in which they are imported:

  • javax.swing.event
  • javax.swing
  • java.awt.event
  • java.awt
  • java.net
  • java.util
  • java.io
  • java.lang

Two BeanShell package classes are also imported by default:

 

  • bsh.EvalError
  • bsh.Interpreter

Finally, we should mention that BeanShell commands may be imported from the classpath. The default commands are imported in the following way:

 

importCommands("/bsh/commands");

We will discuss how to import your own commands in a later section.

 

Tip:
The classes java.awt.List and java.util.List are both imported by default. Because java.util.List is imported later, as part of the java.util package, it takes precedence. To access java.awt.List simply import it in, or the java.awt package again your script. Later imports take precedence.

 

Document Friendly Entities

BeanShell supports special overloaded text forms of all common operators to make it easier to embed BeanShell scripts inside other kinds of documents (e.g XML).

 

@gt >
@lt <
@lteq <=
@gteq >=
@or ||
@and &&
@bitwise_and &
@bitwise_or |
@left_shift <<
@right_shift >>
@right_unsigned_shift >>>
@and_assign &=
@or_assign |=
@left_shift_assign <<=
@right_shift_assign >>=
@right_unsigned_shift_assign >>>=

<!--PAGE BREAK-->

Scripted Methods

You can define define methods in BeanShell, just as they would appear in Java:

 

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

And you can use them in your scripts just as you would any Java method or "built-in" BeanShell command:

 

sum = addTwoNumbers( 5, 7 );

Just as BeanShell variables may be dynamically typed, methods may have dynamic argument and return types. We could, for example, have declared our add() method above like so:

 

add( a, b ) {
    return a + b;
}

In this case, BeanShell would dynamically determine the types when the method is called and attempt to "do the right thing":

 

foo = add(1, 2);
print( foo ); // 3

foo = add("Oh", " baby");
print( foo ); // Oh baby

In the first case Java performed arithmetic addition on the integers 1 and 2. (By the way, if we had passed in numbers of other types BeanShell would have performed the appropriate numeric promotion and returned the correct Java primitive type.) In the second case BeanShell performed the usual string concatenation for String types and returned a String object. This example is a bit extreme, as there are no other overloaded operators like string concatenation in Java. But it serves to emphasize that BeanShell methods can work with loose types.

Methods with unspecified return types may return any type of object (as in the previous example). Alternatively they may also simply issue a "return;" without a value, in which case the effective type of the method is "void" (no type). In either case, the return statement is optional. If the method does not perform an explicit "return" statement and the return type is not explicitly set to void, the value of the last statement or expression in the method body becomes the return value (and must adhere to any declared return typing).

 

Method Modifiers and 'throws' Clauses

The standard Java modifiers may be applied to methods: private / protected / public, synchronized, final, native, abstract, and static.

The synchronized modifier is the only modifier currently implemented. The others are ignored. The 'throws' clause of methods is checked for valid class type names, but is not otherwise enforced.

Synchronized methods are synchronized on the object representing the method's common parent scope, so they behave like Java methods contained in a class. We will return to this topic after discussing scripted objects and "closures".

 

// foo() and bar() are synchronized as if they were in a common class
synchronized foo() { }
synchronized bar() { }

 

Scoping of Variables and Methods

As in Java, a method can refer to the values of variables and method names from the enclosing scope (in Java the "enclosing scope" would be a class). For example:

 

a = 1;
anotherMethod() { ... }

foo() {
    print( a );
	a = a+1;
	anotherMethod();
}

// invoke foo()
foo();      // prints 1
print( a ); // prints 2

Variables and methods are "inherited" from the parent scope in the usual way. In the example above there are just two levels of scope: the top or "global" scope and the scope of the method foo(). Later we'll talk about scripting objects in BeanShell and see that there can be arbitrary levels of scoping involved. But the rules will be the same.

As in Java, a typed variable is not visible outside the scope in which it is declared. So declaring a variable with a type is a way to limit its scope or make a local variable. In BeanShell using an untyped or "loosely" typed variable is also equivalent to declaring a local variable. That is, if you use a variable that has not been defined elsewhere, it defaults to the local scope:

 

a = 1;

foo() {
	a = a + 1; // a is defined in parent scope
	b = 3;     // undefined, defaults local scope
	int c = 4; // declared local scope
}

// invoke foo()
print( a ); // prints 2
print( b ); // ERROR! b undefined
print( c ); // ERROR! c undefined

In the above example the variable 'a' is declared in the global scope. When its value is read and assigned inside of foo() the global value of 'a' will be affected.

The variable 'b' is a usage of an untyped variable. Since 'b' has not been declared or assigned a value in any enclosing scope, it becomes a local variable 'b' in the scope of foo. The variable 'c' is explicitly declared (with a type) in the scope of foo() and is therefore, of course, local to foo().

Later we'll see that BeanShell allows arbitrary nesting of methods. If we were to declare another method inside of foo() it could see all of these variables (a, b, and c) as it is also in the scope of foo().

 

Scoping of Loosely Typed Variables

As in Java, declaring a variable with a type will always make it local. Even if the variable exists in the outer scope, it will be hidden by the local variable declaration. But what of loosely typed variables? As we've seen, untyped variable usage looks just like an ordinary Java assignment. What do we do if we want to make a local variable with the same name as a global one? One answer would be to resort to declaring the variable with a type. But if we wish to continue working with loosely typed variables in this case we have two options: We can explicitly declare a loosely typed variable with the BeanShell 'var' type. Or we can simply qualify our assignment with the 'this.' qualifier.

If you wish to, you can explicitly declare an untyped variable (making it local) using the special type 'var'. e.g.

 

foo() {
	var a = 1;
}
foo();
print( a ); // ERROR! a is undefined!

'var' is a magic type in BeanShell that represents a loose (untyped) variable. The default value of a variable declared with 'var' is null.

Alternately, you can use the scope modifier 'this' to explicitly qualify the variable assignment and make it local.

 

foo() {
	this.a = 1;
}
foo();
print( a ); // ERROR! a is undefined!

In this example we used the modifier 'this' to qualify an untyped variable's scope and make it local. We will explain 'this' and what it means in BeanShell scripted methods in the next section on Scripted Objects.

 

Scope Modifier: 'super'

Within a method, it is possible to explicitly qualify a variable or method reference with the identifier 'super' in order to refer to a variable or method defined in an enclosing scope (the scope in which the method is defined or "higher"). e.g.

 

int a = 42;

foo() {
    int a = 97;
    print( a );
    print( super.a );
}

foo();  // prints 97, 42

As in Java, the 'super' modifiers tells the scoping to begin its search for the variable or method in the parent scope. In the case above, the variable 'a' by default refers to the variable in the local scope. By qualifying 'a' with 'super' we can refer to the variable 'a' in the global scope (the "topmost" scope).

So, we've seen that 'super' can be used to refer to the method's parent context. We'll see in the next section how 'this' and 'super' are used in scripting Objects in BeanShell.

 


<!--PAGE BREAK-->

Scripted Objects

Many people who use BeanShell use it to write scripts that work with existing Java classes and APIs, or perform other kinds of dynamic activities for their own applications at run-time without the aid of a compiler. Often this means writing relatively unstructured code - for example, a sequence of method invocations or loops, all contained in a single script file or eval() statement. In the previous section we saw that BeanShell is also capable of scripting methods, just like Java. Creating methods and new BeanShell commands (which are just methods in their own files) is the natural progression of organizing your scripts into re-usable and maintainable components.

Beyond methods and structured programming lie, of course, objects and the full breadth of object oriented programming. In Java objects are the products of classes. While BeanShell is compatible with standard Java syntax for statements, expressions, and methods, you can't yet script new Java classes within BeanShell. Instead, BeanShell allows you to script objects as "method closures", similar to the way it is done in Perl 5.x, JavaScript, and other object-capable scripting languages. This style of scripting objects (which we'll describe momentarily) is simple and flows very naturally from the style of scripting methods. The syntax, as you'll see, is a straightforward extension of the standard Java concept of referring to an object with a 'this' reference.

 

 

Note:
In standard Java, a method inside of an object (an instance method) may refer to the enclosing object using the special variable 'this'. For example:
    // MyClass.java
    MyClass {
        Object getObject() {
            return this; // return a reference to our object
        }
    }
In the example above, the getObject() method of MyClass returns a reference to its own object instance (an instance of the MyClass object) using 'this'.

 

The 'this' reference

As in most languages, an executing method in BeanShell has its own "local" scope that holds argument (parameter) variables and locally declared variables. For example, in the following code segment any variables that we might use within the foo() method will normally only be visible within the scope of foo() and for the lifetime of one particular foo() method invocation:

 

// Define the foo() method:
foo() {
    int bar = 42;
    print( bar );
}   

// Invoke the foo() method:
foo();  // prints 42

print( bar ); // Error, bar is undefined here 

In the above, the bar variable is local to foo() and therefore not available outside of the method invocation - it is thrown away when the method exits, just like a standard Java local variable.

Now comes the twist - In BeanShell you have the option to "hang on" to the scope of a method invocation after exiting the method by referring to the special 'this' reference. As in Java, 'this' refers to the current object context. The only difference is that in this case the context is associated with the method and not a class instance.

By saving the 'this' reference after the method returns, you can continue to refer to variables defined within the method, using the standard Java "." notation:

 

foo() {
    int bar = 42;
    return this;
}

fooObject = foo();
print( fooObject.bar ); // prints 42!

In the above, the value returned by the foo() method (the 'this' reference) can be thought of as an instance of a "foo" object. Each foo() method invocation effectively creates a new object; foo() is now not just a method, but a kind of object constructor.

In the above case our foo object is not so much an object, but really more of a structure. It contains variables (bar) but no "behavior". The next twist that we'll introduce is that BeanShell methods are also allowed to contain other methods:

 

foo() {
    bar() {
        ...
    }
}

Scripted methods may define any number of nested methods in this way, to an arbitrary depth. The methods are "local" to the method invocation.

Statements and expressions within the enclosing BeanShell method can call their "local" methods just like any other method. (Locally declared methods override outer-more methods like local variables hide instance variables in Java.) The enclosed methods are not directly visible outside of their enclosing method. However, as you might expect, we can invoke them as we would on a Java object, through an appropriate object reference:

 

foo() {
    int a = 42;
    bar() {
        print("The bar is open!");
    }
    
    bar();
    return this;
}

// Construct the foo object
fooObject = foo();     // prints "the bar is open!"
// Print a variable of the foo object
print ( fooObject.a )  // 42
// Invoke a method on the foo object
fooObject.bar();       // prints "the bar is open!"

 

Methods declared inside block structures within methods behave just as if they were declared directly in the method. i.e. there are no block-local methods. For example:

 

foo() {

	bar() { }

	if ( true ) {
		bar2() { }
	}

	return this;
}

In the above example the methods bar() and bar2() are both defined within foo().

 

In the next section we'll return to the topic of variable scoping and go into more depth about how to work with scripted methods and objects.

 


<!--PAGE BREAK-->

Scope Modifiers

Now that we've seen how methods can be nested and treated as objects, we can revisit the topic of variable scope and scope modifiers.

 

'this', 'super', and 'global'

In the "Scripted Methods" section we described the use of 'super' to refer to a method's parent scope (the scope in which the method is defined). And in the previous section we talked about super's brother 'this', which refers

·         import bsh.Interpreter;
Interpreter i = new Interpreter(); // Construct an interpreter
i.set("foo", 5);
                   
// Set variables
i.set("date", new Date() );
Date date = (Date)i.get("date");
   
// retrieve a variable
// Eval a statement and get the result
i.eval("bar = foo*10");
            

System.out.println( i.get("bar") );
// Source an external script file
i.source("somefile.bsh");

分享到:
评论

相关推荐

    用BeanShell来运行java脚本

    标题中的“用BeanShell来运行Java脚本”指的是利用BeanShell这个开源库在Java环境中执行动态的、交互式的Java代码。BeanShell是一个轻量级的Java Scripting引擎,它允许你在运行时执行Java代码,无需编译,极大地...

    java的BeanShell公式执行引擎

    Java的BeanShell是一个轻量级、动态的脚本语言,它是专门为Java平台设计的,允许在运行时执行Java代码或者类似JavaScript的语法。BeanShell在Java应用中常被用来进行快速原型开发、测试以及扩展,它提供了一种简单的...

    导入poi jar包实现使用Beanshell读写Excel文件

    在JMeter测试框架中,我们可以结合使用POI库和BeanShell组件来读取和写入Excel数据,以实现更复杂的测试场景。以下是对这个主题的详细讲解: 首先,Apache POI是一个开源的Java API,它提供了读取、写入和修改MS ...

    JMeter beanShell修改http请求参数

    本文将详细探讨如何使用BeanShell在JMeter中实现这个功能。 首先,BeanShell是JMeter内置的一个脚本引擎,允许用户使用类似Java语法的脚本来处理测试逻辑。在我们的例子中,主要涉及以下三个关键步骤: 1. **引入...

    BeanShell

    BeanShell 是一个轻量级的Java脚本环境,它允许开发者使用类似JavaScript的语法来编写和执行Java代码。BeanShell 的设计目标是提供一个灵活、动态的工具,用于测试、原型设计、脚本以及对Java应用程序进行调试。由于...

    用友NC BeanShell远程代码执行

    # 用友NC BeanShell远程代码执行 # CNVD-2021-30167 ## 漏洞描述 用友NC是一款企业级管理软件,在大中型企业广泛使用。实现建模、开发、继承、运行、管理一体化的IT解决方案信息化平台。用友 NC bsh.[servlet]...

    jmeter-BeanShell简介

    【标题】:“深入理解JMeter中的BeanShell组件” 【描述】:“本文将详细介绍JMeter的BeanShell组件,包括其使用场景、内置变量和方法,帮助读者掌握如何在接口测试中运用BeanShell进行脚本编写。” 【标签】:...

    beanshell java源码解释器

    Beanshell 是一个轻量级的Java源码解释器,它允许你在运行时执行Java代码片段或者完整的脚本。这个工具非常适用于快速测试、调试、以及动态编程任务,因为它的语法接近于标准Java,同时又引入了一些脚本语言的便利...

    用BeanShell实现公式管理

    【标题】: 使用BeanShell构建公式管理系统的实践 【描述】: 在复杂的企业级应用如SCM、CRM和ERP中,常常需要用户根据自身需求调整计算参数,以满足特定时期的业务规则。例如,商品折扣率、员工奖金计算等都需要动态...

    BeanShell帮助文档和jar包

    BeanShell 是一个轻量级的Java脚本语言,它允许开发者使用类似JavaScript的语法来编写和执行Java代码。这个“BeanShell帮助文档和jar包”包含了一切你需要开始使用BeanShell的资源。以下是对BeanShell及其相关文件的...

    beanshell 源码 jar doc sound

    Beanshell 是一个轻量级的Java脚本引擎,它允许用户在运行时直接执行Java语法的脚本。这个压缩包包含三个重要的组成部分:`bsh-2.0b4.jar`、`bshjavadoc.zip` 和 `beanshell` 文件夹,这些都是与Beanshell相关的资源...

    beanshell-2.0b4.src

    Beanshell 是一个轻量级的Java脚本引擎,它允许用户在运行时执行Java语法的脚本。在标题“beanshell-2.0b4.src”中,我们看到的是 Beanshell 的一个源代码版本,2.0b4 表示这是 2.0 版本的第四个β(beta)发布。...

    BeanShell和Mozilla Rhino详细介绍和例子

    BeanShell和Mozilla Rhino是两种在Java环境中用于动态执行和脚本化的工具,它们各自具有独特的特性和用途。 BeanShell是一个轻量级的Java代码解释器,它的主要特点是免费、可嵌入和具备面向对象的脚本语言特性。...

    BeanShell快速入门

    如果你只是要玩一玩BeanShell,你可以在BeanShell的jar文件上双击来起动BeanShell的桌面。但不管怎样,如果你要让BeanShell与你的类与应用程序一起工作就必须将 BeanShell的jar文件加到classpath中。 你可以将...

    how to use beanshell to debug java application

    ### 使用BeanShell调试Java应用程序的关键知识点 #### 一、引言 在评估Java应用程序的安全性时,特别是客户端-服务器架构的应用程序,往往涉及到修改代码、编译、部署、测试等一系列繁琐的过程。当无法获取源代码时...

    beanshell的使用,介绍以及源码

    Beanshell 是一个轻量级的Java脚本引擎,它允许你在运行时动态执行Java代码,也可以用作一个灵活的测试工具。它不只支持标准的Java语法,还提供了与Perl、Python等脚本语言类似的便利特性,如命令行变量、简单的控制...

    BeanShell2.0b5源码

    BeanShell 是一个轻量级的Java脚本引擎,它允许开发者使用类似JavaScript的语法来执行Java代码。在本文中,我们将深入探讨BeanShell 2.0b5的源码,了解其工作原理、核心功能以及它如何为Java开发提供便利。 1. **...

    beanshell所需文件

    Beanshell 是一个轻量级的Java脚本引擎,它允许你在运行时执行和修改Java代码。这个引擎使得开发者能够在应用程序中动态地引入脚本功能,进行测试、调试或者扩展程序的行为。在Java环境中,Beanshell 提供了一种简单...

    运用BeanShell脚本语言进行逻辑判断定义.pdf

    ### BeanShell脚本语言及其逻辑判断应用 #### 一、BeanShell简介 BeanShell是一种轻量级的脚本语言,其语法与Java高度兼容。它不仅支持标准的Java语法,还具备自己的特性和方法,使其成为开发环境中进行快速原型...

Global site tag (gtag.js) - Google Analytics