车执行,弹出一个有Button的GUI界面.
说明:
因为BeanShell是松散类型的脚本语言因此可以直接写:
foo = "Foo";
four = (2 + 2)*2/2;
也就是foo与four均不需要变量类型的声明,给赋什么类型的值,就是什么类型的变量;
print()是BeanShell提供一种简单的打印命令,相当于java中的System.out.println();
脚本中所写的方法范例:
---------------------------------------
int addTwoNumbers( int a, int b ) {
return a + b;
}
sum = addTwoNumbers( 5, 7 ); // 12
也可以使用动态的变量类型(无状态)方法
add(a, b){
return a + b;
}
foo = add(1, 2); // 3
foo = add(1, "2"); //"12"
特别注意:
只要有一个为字符串全部按照字符串处理,
系统不会根据1是数字在前把"2"转换成数字处理;
foo = add("Oh", " baby"); // "Oh baby"
脚本中实现接口
---------------------------------------
实现任何接口需要JDK1.3或者更高,可以使用缺省的java匿名类的语法实现一个接口类,例如:
ActionListener scriptedListener = new ActionListener() {
actionPerformed( event ) { ... }
}
不需要实现接口的所有的方法,只需要实现你使用的方法即可, 如果使用你没有实现的方法,
BeanShell将抛出一个错误,如:
ml = new MouseListener() {
mousePressed( event ) { print("test"); }
// handle the rest
invoke( name, args ) {
print("Method: "+name+" invoked!");
}
}
脚本中定义对象
---------------------------------------
例一:
使用特殊的关键字this可以创建一个对象(根JS类似)
foo() {
print("foo");
x=5;
bar() {
print("bar");
}
return this;
}
myfoo = foo(); // prints "foo"
print( myfoo.x ); // prints "5"
myfoo.bar(); // prints "bar"
例二:
在java标准语言中可以使用this返回一个类的一个实例
// MyClass.java
MyClass {
Object getObject() {
return this; // return a reference to our object
}
}
在这个例子中getObject() 方法是返回MyClass类的一个实例
在BeanShell中对象中的变量只是局部
的变量在对象内可以使用,
在对象外是不可以使用的(不同于前面for-loop,if-else中的使用);
// Define the foo() method:
foo() {
bar = 42;
print( bar );
}
// Invoke the foo() method:
foo(); // prints 42
print(bar); // Error, bar is undefined here
这里的print(bar);会抛出异常:
// Error: EvalError: Undefined argument: bar : at Line: 1 : in file:
: ( bar )
但可以使用this返回对象,使用对象加上"."运算符引用属性(类似JS)
foo() {
bar = 42;
return this;
}
fooObj = foo();
print( fooObj.bar ); // prints 42
同样对象中也可以定义一些方法,例如:
foo() {
int a = 42;
bar() {
print("The bar is open!");
}
//bar();
return this;
}
// Construct the foo object
fooObj = foo(); // prints "the bar is open!"
// Print a variable of the foo object
print ( fooObj.a ) // 42
// Invoke a method on the foo object
fooObj.bar(); // prints "the bar is open!"
也可以定义bar()和foo()也带参数:
foo() {
bar(int a) {
print("The bar is open!" + a);
}
return this;
}
foo().bar(1);
也可以把bar()方法定义到对象外面
foo() {
return this;
}
bar(int a) {
print("The bar is open!" + a);
}
foo().bar(1); //其实就是bar(1);
BeanShell一种松散的脚本语言, 有很多中声明的方法可以使用:
This super global
This 是引用当前对象
Super 是引用父亲对象
Global 是引用最上层对象
super.super.super...foo = 42; // Chain super. to reach the top
global.foo = 42;
BeanShell(Bsh)调用外部Java类的两种方式
-------------------------------------------------------------------------------
在Beanshell中可以调用Java类,有两种方法:
(1) 方法一(直接调用