I wanted to write GUI in Java and processing in Ruby, so I had to handle Ruby and Java classes mutually, so note
$ tree
.
├── out
│ └── production
│ └── JRubyTest
│ └── JrubyTest
│ ├── Main.class
│ └── TestInterface.class
├── ruby
│ ├── TestInterface.jar
│ └── test_class.rb
└── src
└── JrubyTest
├── Main.java
└── TestInterface.java
TestInterface.java
package JrubyTest;
public interface TestInterface {
java.lang.String hello();
}
TestClass.rb
java_import 'JrubyTest.TestInterface'
class TestClass
include TestInterface
def initialize name
@name = name
end
def hello
"hello #{@name}"
end
end
Main.java
package JrubyTest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptContext;
import javax.script.ScriptException;
public class Main {
public static void main(String[] args) {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine rubyEngine = m.getEngineByName("jruby");
ScriptContext context = rubyEngine.getContext();
try {
File file = new File("ruby/test_class.rb");
try {
FileReader reader = new FileReader(file);
rubyEngine.eval(reader);
String name = "'Taro'";
Object testClass = rubyEngine.eval("TestClass.new " + name, context);
if (testClass instanceof TestInterface){
TestInterface test = (TestInterface) testClass;
System.out.println(test.hello());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
Recommended Posts