在jRuby中创建一个接口类型的变量

Create a variable of interface type in jRuby

我想知道如何在 JRuby 中创建一个接口类型的变量并实例化一个对象class。

目前在Java,我们做类似

的事情

MyInterface intrf = new ConcreteClass();

我如何在 jRuby 中做同样的事情。我在下面做了,它抛出错误说找不到 MyInterface 方法。

MyInterface intrf = ConcreteClass.new;

首先,MyInterface intrf = ConcreteClass.new 无效 Ruby。 MyInterface 是常量(例如对 class 的常量引用,尽管它可以是对任何其他类型的引用),而不是引用的类型说明符 - Ruby 因此 J Ruby 是动态类型的。

其次,我假设您想编写一个实现 Java 接口 MyInterface 的 JRuby class 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 wiki for more details, in particular the page JRuby Reference