如何在JRuby中指定Ruby类实现多个Java接口



我知道指定Ruby类在JRuby中实现一个java接口的语法,但我不知道如何指定我们是否希望该类实现多个接口。

我尝试的是:

class MyClass
java_implements 'org.scripthelper.ruby.samples.Script'
java_implements 'org.scripthelper.context.ContextListener'

我也试过:

class MyClass
java_implements 'org.scripthelper.ruby.samples.Script', 'org.scripthelper.context.ContextListener'

但是当我尝试投射

Object o1 = object.toJava(Interface1.class);
Object o2 = object.toJava(ContextListener.class);

但奇怪的是,对于第二个界面,我有以下例外:

rg.jruby.exceptions.TypeError: (TypeError) cannot convert instance of class org.jruby.gen.RubyObject1 to interface org.scripthelper.context.ContextListener
(TypeError) cannot convert instance of class org.jruby.gen.RubyObject1 to interface org.scripthelper.context.ContextListener

我的 ContextListener 接口具有以下 Java 代码:

public void init(ScriptContext context);

我的Ruby类如下:

require 'java'
import 'org.scripthelper.context.ScriptContext'
import 'org.scripthelper.context.ContextListener'
import 'org.scripthelper.context.DefaultScriptContext'
class ScriptClass
java_implements 'org.scripthelper.context.ContextListener', 'org.scripthelper.ruby.samples.Script'
attr_reader :ctx
def init(context)
@ctx = context
end
def execute()
return 10
end
end

只需在接口中使用一个普通的旧包含:

class ScriptClass
include org.scripthelper.context.ContextListener  
include org.scripthelper.ruby.samples.Script
attr_reader :ctx
def init(context)
@ctx = context
end
def execute()
return 10
end
end

最新更新