LoginSignup
3
3

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-09-06

GUIはKotlin、処理はRubyで書きたくて、RubyとJavaのクラスを相互に扱う必要があったのでメモ
JavaのInterfaceをJRubyのクラスに実装してJavaから呼びだすの元ネタ
Kotlinの方がスッキリかける

$ tree
.
├── out
│   └── production
│       └── JRubyKotlin
│           ├── META-INF
│           │   └── JRubyKotlin.kotlin_module
│           ├── MainKt.class
│           └── TestInterface.class
├── ruby
│   ├── TestInterface.jar
│   └── test_class.rb
└── src
    ├── Main.kt
    └── TestInterface.kt
TestInterface.kt
interface TestInterface {
    fun hello(): String
}
test_class.rb
java_import 'TestInterface'

class TestClass
  include TestInterface
  def initialize name
    @name = name
  end

  def hello
    "hello #{@name}"
  end
end
Main.kt
import java.io.File
import javax.script.ScriptEngineManager
import javax.script.ScriptException

fun main(args: Array<String>) {
    val m = ScriptEngineManager()
    val rubyEngine = m.getEngineByName("jruby")
    val context = rubyEngine.context
    try {
        rubyEngine.eval(File("./ruby/test_class.rb").reader())
        val name = "'Taro'"
        val classTest = rubyEngine.eval("TestClass.new " + name, context)
        if (classTest is TestInterface) {
            println(classTest.hello())
        }

    } catch (e: ScriptException) {
        e.printStackTrace()
    }
}
3
3
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
3