【问题标题】:JRuby does not see variable bindingsJRuby 看不到变量绑定
【发布时间】:2023-03-11 07:31:02
【问题描述】:

由于某种原因,jruby 看不到 Java 中设置的变量绑定。根据https://github.com/jruby/jruby/wiki/Embedding-with-JSR-223 此处的文档,以下示例应该可以工作:

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

在我的测试中我得到了异常:

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

我错过了什么吗?

【问题讨论】:

    标签: java jruby jsr223


    【解决方案1】:

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

    System.setProperty("org.jruby.embed.localvariable.behavior", "persistent");
    

    System.setProperty("org.jruby.embed.localvariable.behavior",
    "transient");
    

    在第一种情况下,局部变量在评估中保留,在后一种情况下,它们是每次评估。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 2011-07-02
      相关资源
      最近更新 更多