Problem:
Recently, I encountered a problem when I was doing an application. The client needs to invoke the script information returned from the server side and execute. Where the script type includes Ruby. The code in Java that calls Ruby is roughly the following:
1 String jrubycode= "puts ' Hello World '; 2 New Scriptenginemanager (); 3 ScriptEngine engine = Manager.getenginebyname ("JRuby"); 4 engine.eval (Jrubycode);
Javacallruby
It is found that the last Getenginebyname ("JRuby") always returns NULL. Search the Internet a lot of solutions have not been solved.
Reason:
Currently the JDK is embedded in the engine that supports the most basic JS call, and for other scripting language calls, the corresponding script engine jar package is needed.
Workaround:
Baidu has a lot of no fruit, and finally Google out of the solution.
1. Go to JRuby official website to download the latest JRuby toolkit: Http://jruby.org/download. (Linux downloads the latest tar.gz package directly, Windows downloads 64-bit or 32-bit packages according to the system)
2. Install or unzip the corresponding JRuby to a specific directory, and mimic the Java_home settings jruby_home and path.
3. After the introduction of decompression or installation after the program Lib directory Jruby,jar package into the project.
Know the reason why we need to know why, then we have to explain why the above three steps.
In fact, it can be found that there is a org.jruby.embed.jsr223 directory in this Jruby.jar package, the directory structure is as follows:
We can see the implementation of Jrubyenginefactory, note its Getscriptengine method, which is useful to Scriptcontainer, which represents a script container. View the constructor for this class:
You can see that its construction method calls the Initrubyinstanceconfig method, which is based on the path of Jruby_home to find the corresponding JRuby instance. This is a perfect illustration of the reasons for the previous three steps.
Java calls Ruby code