Sample Program:
Java Code: SampleJsTest .java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class SampleJsTest {
public static void main(String[] args) throws NoSuchMethodException, ScriptException, IOException {
//create a script engine manager
ScriptEngineManager manager = new ScriptEngineManager();
//create a RubyScript engine
ScriptEngine engine = manager.getEngineByName("ruby");
engine.eval(Files.newBufferedReader(Paths.get("C:\\eclipse\\RubyDemoProject\\Test.rb"), StandardCharsets.UTF_8));
Invocable inv = (Invocable)engine;
long a = (long) inv.invokeFunction("add", "3", "2");
System.out.println(">>>"+a);
}
}
Test.rb - ruby file.
Execute the java program.
Place jruby.jar in build path, to avoid the run time exception.
Download jruby.jar from http://jruby.org/download
Java Code: SampleJsTest .java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class SampleJsTest {
public static void main(String[] args) throws NoSuchMethodException, ScriptException, IOException {
//create a script engine manager
ScriptEngineManager manager = new ScriptEngineManager();
//create a RubyScript engine
ScriptEngine engine = manager.getEngineByName("ruby");
engine.eval(Files.newBufferedReader(Paths.get("C:\\eclipse\\RubyDemoProject\\Test.rb"), StandardCharsets.UTF_8));
Invocable inv = (Invocable)engine;
long a = (long) inv.invokeFunction("add", "3", "2");
System.out.println(">>>"+a);
}
}
Ruby script: Test.rb
def add (var1, var2)
return var1.to_i + var2.to_i
end
def add (var1, var2)
return var1.to_i + var2.to_i
end
Test.rb - ruby file.
Execute the java program.
Place jruby.jar in build path, to avoid the run time exception.
Download jruby.jar from http://jruby.org/download
Extract the downloaded zip file.
Now set the java build path for 'jruby.jar'.
Now execute the java program again, after setting the build path for 'jruby.jar'.
Now execute the java program again, after setting the build path for 'jruby.jar'.
No comments:
Post a Comment