gpt4 book ai didi

java - 评估后检索使用的常规变量

转载 作者:行者123 更新时间:2023-12-01 04:12:25 26 4
gpt4 key购买 nike

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

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

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

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

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

你有这样做的想法吗?

ps:以我的法语英语水平很难解释这一点

最佳答案

您需要通过绑定(bind)检索值

    @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;
}

}

关于java - 评估后检索使用的常规变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19793944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com