JRuby: command pattern in Java with Ruby block: why does it work?

家住魔仙堡 提交于 2019-12-08 02:06:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/19784029/jruby-command-pattern-in-java-with-ruby-block-why-does-it-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!