2017-09-19 5 views
0

私は、インターフェイスタイプの変数を作成し、JRubyでImplementingクラスを使用してオブジェクトをインスタンス化する方法を知りました。 Javaで現在 jRubyでインターフェイスタイプの変数を作成

、私たちは

MyInterface intrf =新しいConcreteClassのようなもの();

どのようにjRubyで同じことをするのですか?私は以下の通り、MyInterfaceメソッドが見つからないというエラーが表示されます。

MyInterface intrf = ConcreteClass.new;

答えて

0

まず、MyInterface intrf = ConcreteClass.newは有効なRubyではありません。 MyInterfaceは、参照の型指定子ではなく、定数(クラスへの定数参照など)ですが、RubyではJRubyが動的に型指定されています。

第2に、JavaインタフェースMyInterfaceを実装するJRubyクラスConcreteClassを作成したいとします。ここでは、Javaパッケージ 'com.example'にあります。

require 'java' 
java_import 'com.example.MyInterface' 

class ConcreteClass 
    # Including a Java interface is the JRuby equivalent of Java's 'implements' 
    include MyInterface 

    # You now need to define methods which are equivalent to all of 
    # the methods that the interface demands. 

    # For example, let's say your interface defines a method 
    # 
    # void someMethod(String someValue) 
    # 
    # You could implements this and map it to the interface method as 
    # follows. Think of this as like an annotation on the Ruby method 
    # that tells the JRuby run-time which Java method it should be 
    # associated with. 
    java_signature 'void someMethod(java.lang.String)' 
    def some_method(some_value) 
    # Do something with some_value 
    end 

    # Implement the other interface methods... 
end 

# You can now instantiate an object which implements the Java interface 
my_interface = ConcreteClass.new 

は、ページ JRuby Reference特に、詳細は JRuby wikiを参照してください。

関連する問題