从JRuby代码更改java变量?

时间:2011-07-28 21:08:46

标签: java variables jruby

正如标题所说,我想从我的jruby代码中改变我的变量

更具体地说,我的Java代码中有一个整数,它没有任何值,而且我用我的JRuby代码给这个变量一个值,但我不知道怎么做。

这是我使用JRuby代码的程度。

require 'java'
puts "Set player health here"
playerHealth = 3 # Setting player health here!

但还没有在java中写过任何东西。到目前为止,这几乎就是我所有的......

1 个答案:

答案 0 :(得分:2)

根据我的理解,您正在尝试从Java调用JRuby引擎,因此您可以执行类似这样的操作来修改JRuby中的Java变量:

import javax.script.*;

public class EvalJRubyScript {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager factory = new ScriptEngineManager();

        int playerHealth = 0;

        ScriptEngine engine = factory.getEngineByName("jruby");
        ScriptContext context = engine.getContext();
        context.setAttribute("playerHealth", playerHealth, ScriptContext.ENGINE_SCOPE);

        try {
            engine.eval("$playerHealth = 42");
            playerHealth = (Integer)context.getAttribute("playerHealth",  ScriptContext.ENGINE_SCOPE);

            System.out.println(playerHealth);
        } catch (ScriptException exception) {
            exception.printStackTrace();
        }
    }
}

请注意,脚本中playerHealth是一个全局变量。

如果要加载外部JRuby脚本而不是评估代码,请查看this link以获取更多详细信息。