GroovyEnginey与CachingGroovyEngine行为区别

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不能。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值