BeanShell开发小结

BeanShell 是一个具有面向对象脚本语言特性的Java代码解释器开源组件
http://www.beanshell.org/


beanshell 三种调用方式:
a. BeanShell GUI (java bsh.console)
public class BeanShellGui {
public static void main(String[] args) {
Console.main(args);
}
}
b. BeanShell 命今行/文本 (java bsh.Interpreter)
例如: Interpreter i = new Interpreter();
i.eval("ss = 4 + 6");
System.out.println(i.get("ss")); //输出结果 10


c. BeanShell 脚本文件 (java bsh.Interpreter fileName)
例:
1. 新建一个script.bsh
script.bsh代码如下:
add(a,b) {
return a + b;
}
2. 测试代码:
int main(String[] args) {
Interpreter i = new Interpreter();
i.source("script.bsh);
i.eval("ss = add(1,2)");
System.out.println(i.get("ss")); //输出结果 3

i.eval("sdf = add(\"hello\",\" world\")");
System.out.println(i.get("sdf")); //输出结果 hello world
}

Java 语句与表达式
BeanShell 支持标准的Java 语句,表达式,方法定义. 语句和表达式的内容可以是:变量,宣告,赋值,方法调用,循环,判断等
BeanShell 的变量是宽类型的, 用户在定义变量,或方法时可以不指定具体的类型。 在类型不匹配时,BeanShell将抛出一个类型错误.

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);

BeanShell 命今
BeanShell 内置的*.bsh命今函数,
提示**:BeanShell 命令并不是真的"内建"其中的,而是作为脚本方法自动从classpath载入, 在/bsh/commands目录下
常用的BeanShell函数:
source(), run() - 将一个bsh脚本读到解释器或运行在另一个解释器。
frame() - 显示一个Frame或JFrame的GUI组件.
load(), save() - 载入和保存一个序列化的对象到一个文件.
cd(), cat(), dir(), pwd(), etc. - 类unix的shell命令。
exec() - 运行一个本地的程序。
javap() - 打印一个对象的方法和字段,类似于Java的javap命令。
setAccessibility() - 开启无限制的存取private 和protected的组件。

BeanShell脚本方法
你可以在bsh中宣告和使用方法,就像在java的类中一样:
如:
int addTwoNumbers( int a, int b ) {
return a + b;
}
sum = addTwoNumbers( 5, 7 ); // 12
BeanShell 支持动态类型参数和返回类型
add( a, b ) {
return a + b;
}
foo = add(1, 2); // 3
foo = add("Oh", " baby"); // "Oh baby"

BeanShell 定义一类实现某一接口
用Java内部类的语法实现Interface
Interface iface = new Interface() {
public void todo() {
....
}
};


应用程序调用BeanShell
Interpreter i = new Interpreter();
i.eval("int i = 1+2");

int j = (Integer) i.get("i");

http://blog.csdn.net/xymyeah/archive/2006/05/08/713237.aspx
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值