2017-09-19 1 views
0

Ich frage mich, wie man eine Variable des Interface-Typs erstellt und ein Objekt mit implementierender Klasse in JRuby instanziiert.Erstellen Sie eine Variable des Schnittstellentyps in jRuby

Derzeit in Java, wir tun so etwas wie

MyInterface INTRF = new ConcreteClass();

Wie mache ich das gleiche in jRuby. Ich habe unten und es wirft mich Fehler, die MyInterface-Methode nicht gefunden.

MyInterface intrf = ConcreteClass.new;

Antwort

0

Erstens ist MyInterface intrf = ConcreteClass.new nicht gültig Ruby. MyInterface ist eine Konstante (z. B. ein konstanter Verweis auf eine Klasse, obwohl sie eine Referenz auf einen anderen Typ sein könnte), kein Typspezifizierer für eine Referenz - Ruby und daher wird JRuby dynamisch typisiert.

Zweitens nehme ich an, dass Sie eine JRuby-Klasse ConcreteClass schreiben möchten, die die Java-Schnittstelle MyInterface implementiert, die - zum Beispiel - hier im Java-Paket 'com.example' steht.

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 

Siehe JRuby wiki für weitere Details, insbesondere die Seite JRuby Reference.

Verwandte Themen