程序里要提供复杂函数的的动态输入,于是就使用了BeanShell,我对BeanShell只是初次接触,我是这样解决的:Interpreter interpreter=new Interpreter();
try {
double[] x={2.15,1.00};
interpreter.set("var",x);
interpreter.source("c:/x.bsh");
System.out.println(interpreter.get("ret"));

} catch (EvalError e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}x.bsh为一个脚本文件如下:double ret=0.0;
for(int i=0;i<var.length;i++){
ret+=var[i];
}
但由于实际应用中的函数远比例子要复杂千万倍,而且要调用执行许多次(大约平均在1E4次左右);这样就出现了一个效率问题;要反复调用beanshell的interrepter,有没有一个好的解决方法,一次调用beanshell的interrepter,获得一个函数类,然后就直接使用这个函数类就可以了,请各位不吝赐教?谢谢

解决方案 »

  1.   

    BeanShell文档里关于效率的说明:Parsing and Performance
    It is useful to have a high level understanding how BeanShell works with scripts to understand performance issues.The first time a script is read or sourced into an interpreter, BeanShell uses the parser to parse the script internally to an AST. The AST consists of Java object representations of all of the language structures and objects. The AST consists of Java classes, but is not the same as compiled Java code. When the script is "executed" BeanShell steps through each element of the AST and tells it to perform whatever it does (e.g. a variable assignment, for-loop, etc.). This execution of the ASTs is generally much faster than the original parsing of the text of the method. It is really only limited by the speed of the application calls that it is making, the speed of the Java reflection API, and the efficiency of the implementation of the structures in BeanShell.When parsing "line by line" through a BeanShell script the ASTs are routinely executed and then thrown away. However the case of a BeanShell method declaration is different. A BeanShell method is parsed only once: when it is declared in the script. It is then stored in the namespace like any variable. Successive invocations of the method execute the ASTs again, but do not re-parse the original text.This means that successive calls to the same scripted method are as fast as possible - much faster than re-parsing the script each time. You can use this to your advantage when running the same script many times simply by wrapping your code in the form of a BeanShell scripted method and executing the method repeatedly, rather than sourcing the script repeatedly. For example:// From Java
    import bsh.Interpreter;
    i=new Interpreter();// Declare method or source from file
    i.eval("foo( args ) { ... }");i.eval("foo(args)"); // repeatedly invoke the method
    i.eval("foo(args)");
    ...In the above example we defined a method called foo() which holds our script. Then we executed the method repeatedly. The foo() method was parsed only once: when its declaration was evaluated. Subsequent invocations simply execute the AST. 你的 interpreter.source("c:/x.bsh"); 应该只运行一次,之后反复调用其中定义的方法时应该会快一些。