BeanShell 是一个小的,免费的,可以内嵌的java源代码解释器,它具有面向对象脚本语言的特性,并且是用java实现的。Beanshell 可以动态地执行标准的java语句,还自带简单的脚本命令和语法。
Beanshell 的一个重要用途就是:通过建立一个BeanShell解释器,使用eval()或source()命令,你可以在你的应用程序中求文本表达式的值和运行脚本。就像matlab中的eval()函数一样。
例如:
Interpeter bsh = new Interpreter();
// Evaluate statements and expressions
bsh.eval("foo=Math.sin(0.5)");
bsh.eval("bar=foo*5; bar=Math.cos(bar);");
bsh.eval("for(i=0; i<10; i++) { print(/"hello/"); }");
// same as above using java syntax and apis only
bsh.eval("for(int i=0; i<10; i++) { System.out.println(/"hello/"); }");
//Source from files or streams
bsh.source("myscript.bsh"); // or bsh.eval("source(/"myscript.bsh/")");
// Use set() and get() to pass objects in and out of variables
bsh.set( "date", new Date() );
Date date = (Date)bsh.get( "date" );
// This would also work:
Date date = (Date)bsh.eval( "date" );
bsh.eval("year = date.getYear()");
Integer year = (Integer)bsh.get("year"); // primitives use wrappers
然而在前几天的一个应用中我在一个类中预先实现了一些方法,我需要通过读一个文件来决定到底该调用哪个方法,文件中保存着方法的名字。于是我用了类似于以下的语句:
import bsh.Interpreter;
public class Main {
public String str = "hello interpreter";
public static void main(String[] args)
{
Main mainObj = new Main();
mainObj.doProcess();
}
public void doProcess()
{
Interpreter bshInterpreter = new Interpreter();
try {
bshInterpreter.eval("printText()");
} catch (bsh.EvalError ee) {
System.out.println(ee.toString());
}
}
private void printText()
{
System.out.println(str);
}
}
但是报错说找不到printText()方法;
Sourced file: inline evaluation of: "printText();'' : Command not found: printText()
改进的方法是:
1. private void printText() 需要改为public
2. bshInterpreter.eval("printText()"); 改为
bshInterpreter.set("thisObject", this); // 将this object 赋给变量thisObject
bshInterpreter.eval("thisObject."+"printText()"); // this.printText()
21-04-2010, Stavanger