我正在使用像我的java应用程序中的评估器/编译器那样的groovy。 例如,我通过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()方法但它返回所有groovy会话变量而不是最后使用的变量。
你有想法吗?
ps:用我的法语英语水平不容易解释
答案 0 :(得分: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;
}
}