Frage

I am learning how to integrate Java library with Ruby code and come to the following question.

I have a command pattern implemented in Java, as follows:

public interface Command {
  public String execute(String param);
}

public class CommandRunner {

  public String run(Command cmd, String param) {
    return cmd.execute(param)+" [this is added by run method]";
  }
}

When I import that to JRuby program I can implement Ruby class that respond_to? :execute with one parameter and pass it to the CommandRunner.new.run. That works and that's clear.

But I can also do this:

def put_through_runner(param, &block)
  CommandRunner.new.run block, param
end

p = put_through_runner "through method" do |param|
  "Cmd implementation in block, param: #{param}"
end

puts p

Instead of passing to Java CommandRunner an object implementing the execute method I pass it a block of code, that does not implement the method. And It works: calls the block as if it was implementation of the execute method! How is that possible? What does JRuby do with the block when passing it to Java? If I had the CommandRunner implemented in Ruby the above code would not work.

War es hilfreich?

Lösung

The reason that this works is a feature called 'closure conversion' (see docs here). What happens is that the block you pass is converted into a Proc object with a proxy that invokes the code in the block for any method that is called on the object.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top