簡體   English   中英

如何在 JRuby 中指定 Ruby class 實現幾個 java 接口

[英]How to specify in JRuby that a Ruby class implements several java interfaces

I know the syntax to specify that a Ruby class implements one java interface in JRuby, but I don't know how to specify if we want the class to implement more than one interface.

我嘗試的是:

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 class如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM