Java程序中我们问了增强功能,现在都提供用户可以编程的接口,例如允许使用js, groovy等脚本语言与java编写的系统进行交互。在使用groovy时,我们通常会使用org.apache.bsf.BSFManager注册脚本引擎, 那么对于Groovy有两种引擎,该如何选择了。下面给出例子。
package com.xyz.zhangsan;
import org.apache.bsf.BSFEngine;
import org.apache.bsf.BSFException;
import org.apache.bsf.BSFManager;
public class GroovyEngineTest {
public static void main(String[] args) {
try {
String myScript1 = "public class BSFHelloWorld {\n public static void main("
+ "String[] args ) { println(\'BSF: main: Hello World!\'); }\n };";
String myScript2 = "import BSFHelloWorld;\n inst = new BSFHelloWorld();\n";
BSFManager bsfm = new BSFManager();
// Problem can be resolved by uncommenting the line below:
/*BSFManager.registerScriptingEngine("groovy", "org.codehaus.groovy.bsf.CachingGroovyEngine",
new String[]{"groovy", "gy"});*/
BSFEngine anEngine = bsfm.loadScriptingEngine("groovy");
anEngine.exec("Step HelloWorld1", 0, 0, myScript1);
System.out.println("script2");
anEngine.exec("Step HelloWorld2", 0, 0, myScript2);
}
catch (BSFException bse) {
bse.printStackTrace();
}
}
}
添加上groovy和对应的bsf, commons-logging这三个jar包就可以执行。 执行后输出
BSF: main: Hello World!
script2
exception from Groovy: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Step_HelloWorld2: 1: unable to resolve class BSFHelloWorld
@ line 1, column 1.
import BSFHelloWorld;
可以看到第一个脚本正常执行,已经输出BSF: main: Hello World!。 但是第二个脚本因为找不到BSFHelloWorld类,无法执行。 我们可以看到其实第一个脚本中已经定义了BSFHelloWorld类。 这是只要我们取消BSFManager.registerScriptingEngine(“groovy”, “org.codehaus.groovy.bsf.CachingGroovyEngine”,
new String[]{“groovy”, “gy”});的注释, 在重新执行。一切就workweek了。
When using BSF to interact with GroovyEngine it was seen that a Groovy class that was created as a result of a previous execution was not available for subsequent execution when GroovyEngine was used.
If CachingGroovyEngine was used, it would work.
就是CachingGroovyEngine能够使用之前执行的类,而GroovyEngine不能。