1

我正在使用 groovy,就像我的 java 应用程序中的评估器/编译器一样。例如,我通过 groovy 绑定设置了一个变量 (HS1 = 1, HS2 = 5)

binding.setVariable("HS1", 1);
binding.setVariable("HS2", 5);

我启动一个操作并通过 groovy 评估方法捕获结果(HS3 = HS1 + HS2)

value = (Number) shell.evaluate("HS3=HS1+HS2");

对于我的应用程序,我想在上次操作期间检索使用的变量(在本例中为 HS1 和 HS2)。我正在尝试使用 binding.getVariables() 方法,但它返回所有常规会话变量,而不是最后使用的变量。

你有这样做的想法吗?

ps:以我的法语英语水平不容易解释

4

1 回答 1

0

您需要使用绑定检索值

    @org.junit.Test
public void test(){
    Binding binding = new Binding();
    binding.setVariable("HS1", 1);
    binding.setVariable("HS2", 5);
  //binding.setVariable("HS3", new Integer()); 
    GroovyShell gs = new GroovyShell(binding);
    binding.beginCut(new LinkedHashMap<String, Object>());
    Object o  = gs.evaluate("HS3=HS1+HS2");
    logger.info("GroovyTest.test: end cut");
    logger.info("GroovyTest.test: "+o);
    Map<String, Object> properties = binding.endCut();
    logger.info("GroovyTest.test: ------");
    for (Object v : properties.keySet()){
        logger.info("GroovyTest.test: "+v);
    }
    Number sResult = (Number)binding.getVariable( "HS3" ) ;
    logger.info(sResult);
}



 public class MyBinding extends Binding {
private static org.apache.log4j.Logger logger = org.apache.log4j.Logger
        .getLogger(MyBinding.class);

@Override
public Object getVariable(String name) {
    logger.info("MyBinding.getVariable: request " + name);
    Object value = super.getVariable(name);
    //filter the requested variable
    if (properties != null) {
        properties.put(name, value);
    }
    return value;
}

Map<String, Object> properties = null;

public void beginCut(Map<String, Object> properties) {
    this.properties = properties;
}

public Map<String, Object> endCut() {
    Map<String, Object> properties = this.properties;
    this.properties = null;
    return properties;
}

}

于 2013-11-05T18:17:17.603 回答