首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JRuby没有看到变量绑定

JRuby没有看到变量绑定
EN

Stack Overflow用户
提问于 2015-10-06 11:45:45
回答 1查看 243关注 0票数 1

由于某些原因,jruby没有看到Java中设置的变量绑定。根据这里的文档https://github.com/jruby/jruby/wiki/Embedding-with-JSR-223,下面的示例应该工作:

代码语言:javascript
复制
public static void main(String[] args) throws ScriptException {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("jruby");
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("owner", "Otto");
    engine.eval("puts \"hello #{owner}\"", bindings);
}

在我的测试中,我得到了一个例外:

代码语言:javascript
复制
NameError: undefined local variable or method `owner' for main:Object
  <top> at <script>:1
Exception in thread "main" javax.script.ScriptException: org.jruby.embed.EvalFailedException: (NameError) undefined local variable or method `owner' for main:Object

我错过什么了吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-07 13:47:59

造成这种行为的原因是,默认情况下,局部变量不能在Java和JRuby之间共享,而只能在全局变量之间共享。参见:关于局部变量行为的https://github.com/jruby/jruby/wiki/RedBridge。解决方案是显式地设置

代码语言:javascript
复制
System.setProperty("org.jruby.embed.localvariable.behavior", "persistent");

代码语言:javascript
复制
System.setProperty("org.jruby.embed.localvariable.behavior",
"transient");

在第一种情况下,局部变量是跨评估保存的,而在后一种情况下,则是每个评估。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32969116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档