0
我想知道如何創建一個接口類型的變量並在JRuby中實現一個實現類的對象。在jRuby中創建接口類型的變量
在Java中目前,我們這樣做
MyInterface的intrf =新的具體類();
如何在jRuby中執行相同的操作。我在下面做了,它會引發錯誤,說MyInterface方法未找到。
MyInterface intrf = ConcreteClass.new;
我想知道如何創建一個接口類型的變量並在JRuby中實現一個實現類的對象。在jRuby中創建接口類型的變量
在Java中目前,我們這樣做
MyInterface的intrf =新的具體類();
如何在jRuby中執行相同的操作。我在下面做了,它會引發錯誤,說MyInterface方法未找到。
MyInterface intrf = ConcreteClass.new;
首先,MyInterface intrf = ConcreteClass.new
是無效的Ruby。 MyInterface
是一個常量(例如對類的常量引用,儘管它可能是對任何其他類型的引用),而不是引用的類型說明符--Ruby因此JRuby是動態類型的。其次,我假設你想編寫一個JRuby類ConcreteClass
,它實現了Java接口MyInterface
,我在這裏說的是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 wiki,尤其是頁JRuby Reference。