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。