java - JRuby 看不到变量绑定(bind)

标签 java jruby jsr223

由于某种原因,jruby 看不到 Java 中设置的变量绑定(bind)。根据此处的文档,以下示例应该是 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 之间共享,只能共享全局变量。请参阅:https://github.com/jruby/jruby/wiki/RedBridge关于局部变量的行为。解决方案是显式设置

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

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

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

关于java - JRuby 看不到变量绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32969116/

相关文章:

JRuby:Java 和 Ruby 类型/类之间的映射/转换的文档?

java - Groovy ScriptingEngine 线程安全吗?

java - 检查某个东西是否等于不同的东西java

java - Android:如何使异步任务 hibernate ,同时评估某些条件

java - 新定义的环境变量在 WSL2 之外看不到?

mysql - 在 JRuby 上使用 ActiveRecord 对 MariaDB 的首次查询需要 5 分钟以上才能执行

java - 当部署为 WAR 时,JRuby 中的线程安全 Resque Worker

java - 以看似随机的间隔获取 NullPointerException,不知道为什么

java - JMeter OutOfMemory 由于 groovy 脚本创建了多个类而导致

groovy - 如何在JSR223的Groovy类中使用JMeter的内部方法(vars.get()等)