避免为每个记录重新初始化Groovy Shell。

huangapple go评论118阅读模式
英文:

Avoiding reinitialsation of groovy shell for each record

问题

  1. for(int i = 0; i < records.length; i++){
  2. Binding binding=new Binding();
  3. binding.setVariable("val1",records[i][0]);
  4. binding.setVariable("val2",records[i][1]);
  5. binding.setVariable("val3",records[i][2]);
  6. GroovyShell shell=new GroovyShell(binding);
  7. Object value = shell.evaluate(code);
  8. System.out.println(value.toString());
  9. };

我不想为每个记录重复创建 GroovyShell,但我看不到其他选项。从我所了解的情况来看,我不能在同一个 GroovyShell 上提供新的绑定,因为绑定只能在创建 shell 时提供,不能在之后更改。

我尝试过在创建 GroovyShell 后更改绑定对象,但是会出现错误。

我是否有其他方法,可以避免为每个记录重新初始化 GroovyShell?我只想将变量 record[i][0]、recordi、record[i][2] 传递给 shell。

英文:

I am trying to implement the following code:-

  1. for(int i = 0; i &lt; records.length; i++){
  2. Binding binding=new Binding();
  3. binding.setVariable(&quot;val1&quot;,records[i][0]);
  4. binding.setVariable(&quot;val2&quot;,records[i][1]);
  5. binding.setVariable(&quot;val3&quot;,records[i][2]);
  6. GroovyShell shell=new GroovyShell(binding);
  7. Object value = shell.evaluate(code);
  8. System.out.println(value.toString());
  9. };

I don't want to create GroovyShell again and again for each record, but I am not able to see another option. From what I have seen, I can't provide a new binding to the same groovy shell, since binding can be provided only while creating the shell and not afterwards.

I have tried changing the binding object after creating groovy shell but it is giving me an error.

Do I have an alternative to reinitializing the groovy shell again and again for each record? I just want to pass the variables record[i][0],recordi,record[i][2] to the shell.

答案1

得分: 1

  1. use [GroovyShell.parse(code)][1]
  2. Script script = new GroovyShell().parse(code);
  3. for(int i = 0; i < records.length; i++){
  4. Binding binding=new Binding();
  5. binding.setVariable("val1",records[i][0]);
  6. binding.setVariable("val2",records[i][1]);
  7. binding.setVariable("val3",records[i][2]);
  8. script.setBinding(binding);
  9. Object value = script.run();
  10. System.out.println(value.toString());
  11. };
  1. <details>
  2. <summary>英文:</summary>
  3. use [GroovyShell.parse(code)][1]

Script script = new GroovyShell().parse(code);

for(int i = 0; i < records.length; i++){
Binding binding=new Binding();
binding.setVariable("val1",records[i][0]);
binding.setVariable("val2",recordsi);
binding.setVariable("val3",records[i][2]);
script.setBinding(binding);
Object value = script.run();
System.out.println(value.toString());
};

  1. [1]: https://docs.groovy-lang.org/latest/html/api/groovy/lang/GroovyShell.html#parse(java.lang.String)
  2. </details>

huangapple
  • 本文由 发表于 2020年4月6日 20:09:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/61059526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定