简体   繁体   English

从JRuby代码更改java变量?

[英]change java variables from JRuby code?

As title says i whant to change my variables in java from my jruby code 正如标题所说我想从我的jruby代码中改变java中的变量

To be more specific i have an integer in my Java code which has no value yet, And i whant with my JRuby code give this variable an value, But i have no idea how to do this. 更具体地说,我的Java代码中有一个整数没有值,而且我用我的JRuby代码给这个变量一个值,但我不知道怎么做。

This is how far i got with the JRuby code.. 这是我用JRuby代码得到的程度。

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

But have not yet wrote anything in java. 但还没有在java中写任何东西。 This is pretty much all I have so far.. 到目前为止,这几乎就是我所有的......

From what I understand, you are trying to invoke the JRuby engine from Java, so you could do something like this to modify a Java variable in JRuby: 根据我的理解,您正在尝试从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();
        }
    }
}

Note that in the script playerHealth is a global variable. 请注意,在脚本中playerHealth是一个全局变量。

Check out this link for more details if you want to load an external JRuby script rather than evaluating code. 如果要加载外部JRuby脚本而不是评估代码,请查看此链接以获取更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM