简体   繁体   中英

Pass a Ruby block to a Java method

I need my JRuby method to recieve a report of what is going on in a Java method and act accordingly:

def my_long_running_method
  # ... do stuff ...

  jObject.count_all_disk_files do |number_of_files|
    stream.write "#{number_of_files} files found so far."
  end

  # ... do more stuff ...
end

I saw this question but I couldn't understand what I need to do.

I've known Ruby for a long time and a little of Java. This project needs to be JRuby because of old Java code that needs to be integrated with new Ruby code.

For a complete reference, see the Calling Java From JRuby wiki page , specifically the section about closure conversion . The short answer to your question is that your Java method count_all_disk_files will need to accept an interface with a single method (a "functional interface"). Then JRuby will be able to automatically implement that interface with the code from the block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM