在Java中嵌入Groovy(绑定) [英] Embedding Groovy in Java (Binding)

查看:650
本文介绍了在Java中嵌入Groovy(绑定)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将变量绑定到Groovy,并从Groovy返回zu Java:



Java代码:

  Binding binding = new Binding(); 
binding.setVariable(SRESULT,foo);
GroovyShell gs =新GroovyShell(绑定);
gs.evaluate(script);
String sResult =(String)gs.getContext()。getVariable(SRESULT);
System.out.println(FROM GROOVY:+ sResult);

Groovy代码:

  class Est {
static SRESULT
public static void main(String [] args){
println'从Java开始:'+ SRESULT
SRESULT ='bar '
}
}

输出:

 从Java:foo 
FROM GROOVY:foo

我的问题:我想在Groovy中更改 SRESULT ,并有权访问Java中的Value。



任何人都可以帮助我吗? 解决方案

绑定仅适用于脚本 。如果你的Groovy代码是一个脚本,也就是没有周围类体的 main 方法的内容

  println'从Java:'+ SRESULT 
SRESULT ='bar'

那么它会产生你期望的结果。特别是你不能在脚本中声明 SRESULT 变量,即

  def SRESULT ='bar'

would not <工作。这是因为声明(使用 def 或具有显式类型)在脚本内创建局部变量,它们不会分配给绑定。


I try to Bind Variables to Groovy and from Groovy back zu Java:

Java code:

Binding binding = new Binding();
binding.setVariable("SRESULT", "foo");
GroovyShell gs = new GroovyShell(binding);
gs.evaluate(script);
String sResult = (String) gs.getContext().getVariable("SRESULT");
System.out.println("FROM GROOVY: " + sResult);

Groovy Code:

class Est {  
  static SRESULT
  public static void main(String[] args) {
    println 'From Java: '+SRESULT
    SRESULT = 'bar'
  }
}

Output:

From Java: foo
FROM GROOVY: foo

My Question: I want to change SRESULT in Groovy and have access to the Value in Java.

Can anybody help me?

解决方案

The binding only applies to scripts, not to classes. If your Groovy code were a script, i.e. just the content of the main method without the surrounding class body

println 'From Java: '+SRESULT
SRESULT = 'bar'

then it would produce the result you expect. In particular you must not declare the SRESULT variable in the script, i.e.

def SRESULT = 'bar'

would not work. This is because the declarations (with def or with an explicit type) create local variables within the script, they do not assign to the binding.

这篇关于在Java中嵌入Groovy(绑定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆