LoginSignup
3
0

More than 5 years have passed since last update.

JavaのInterfaceをJRubyのクラスに実装してJavaから呼びだす

Last updated at Posted at 2017-09-05

GUIはJava、処理はRubyで書きたくて、RubyとJavaのクラスを相互に扱う必要があったのでメモ

$ 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();
        }
    }
}
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0